Description: Fix ivy dependencies. * Remove svgSalamander * Add jsvg ** com.github.weisj.jsvg.annotations https://github.com/weisJ/jsvg/archive/refs/tags/v2.1.0.tar.gz ** com.google.errorprone.annotations https://repo1.maven.org/maven2/com/google/errorprone/error_prone_annotations/2.25.0/error_prone_annotations-2.25.0-sources.jar ** org.intellij.lang.annotations https://repo1.maven.org/maven2/com/intellij/annotations/12.0/annotations-12.0-sources.jar ** aQute.bnd.annotation https://repo1.maven.org/maven2/biz/aQute/bnd/biz.aQute.bnd.annotation/7.1.0/biz.aQute.bnd.annotation-7.1.0-sources.jar *** osgi.annotation https://repo1.maven.org/maven2/org/osgi/osgi.annotation/8.1.0/osgi.annotation-8.1.0-sources.jar **** org.osgi.namespace.extender https://repo1.maven.org/maven2/org/osgi/org.osgi.namespace.extender/1.0.1/org.osgi.namespace.extender-1.0.1-sources.jar **** org.osgi.namespace.service https://repo1.maven.org/maven2/org/osgi/org.osgi.namespace.service/1.0.0/org.osgi.namespace.service-1.0.0-sources.jar **** org.osgi.resource https://repo1.maven.org/maven2/org/osgi/org.osgi.resource/1.0.0/org.osgi.resource-1.0.0-sources.jar ***** org.osgi.dto https://repo1.maven.org/maven2/org/osgi/org.osgi.dto/1.0.0/org.osgi.dto-1.0.0-sources.jar **** org.osgi.service.serviceloader https://repo1.maven.org/maven2/org/osgi/org.osgi.service.serviceloader/1.0.0/org.osgi.service.serviceloader-1.0.0-sources.jar Author: Bas Couwenberg Bug: https://josm.openstreetmap.de/ticket/24839 Forwarded: not-needed --- a/src/com/kitfox/svg/A.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on January 26, 2004, 1:56 AM - */ - -package com.kitfox.svg; - -import com.kitfox.svg.xml.StyleAttribute; -import java.net.URI; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class A extends Group -{ - public static final String TAG_NAME = "a"; - - URI href; - String title; - - /** Creates a new instance of Stop */ - public A() - { - } - - @Override - public String getTagName() - { - return TAG_NAME; - } - - @Override - protected void build() throws SVGException - { - super.build(); - - StyleAttribute sty = new StyleAttribute(); - - if (getPres(sty.setName("xlink:href"))) - { - href = sty.getURIValue(getXMLBase()); - } - - if (getPres(sty.setName("xlink:title"))) - { - title = sty.getStringValue(); - } - } - - /** - * Updates all attributes in this diagram associated with a time event. - * Ie, all attributes with track information. - * @return - true if this node has changed state as a result of the time - * update - */ - @Override - public boolean updateTime(double curTime) throws SVGException - { - boolean changeState = super.updateTime(curTime); -// if (trackManager.getNumTracks() == 0) return false; - - //Get current values for parameters - StyleAttribute sty = new StyleAttribute(); - - if (getPres(sty.setName("xlink:href"))) - { - href = sty.getURIValue(getXMLBase()); - } - - if (getPres(sty.setName("xlink:title"))) - { - title = sty.getStringValue(); - } - - return changeState; - } -} --- a/src/com/kitfox/svg/BufferPainter.java +++ /dev/null @@ -1,215 +0,0 @@ -package com.kitfox.svg; - -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.Rectangle; -import java.awt.geom.AffineTransform; -import java.awt.geom.Point2D; -import java.awt.image.BufferedImage; -import java.awt.image.ImageObserver; -import java.util.Collections; -import java.util.List; -import java.util.Objects; -import java.util.stream.Collectors; - -public class BufferPainter -{ - public static final boolean DEBUG_PAINT = false; - - public static class Cache - { - private final BufferedImage img; - private final Rectangle bounds; - private final AffineTransform transform; - - public Cache(BufferedImage img, Rectangle bounds, AffineTransform transform) - { - this.img = img; - this.bounds = bounds; - this.transform = transform; - } - - boolean isCompatible(AffineTransform tx) - { - return tx.getScaleX() == transform.getScaleX() - && tx.getScaleY() == transform.getScaleY() - && tx.getShearX() == transform.getShearX() - && tx.getShearY() == transform.getShearY(); - } - - Rectangle getBoundsForTransform(AffineTransform tx) - { - double dx = tx.getTranslateX() - transform.getTranslateX(); - double dy = tx.getTranslateY() - transform.getTranslateY(); - return new Rectangle((int) (bounds.x + dx), (int) (bounds.y + dy), - bounds.width, bounds.height); - } - } - - public static void paintElement(Graphics2D g, RenderableElement element) throws SVGException - { - if (element.cachedMask != null - || (element.filter != null && !element.filter.filterEffects.isEmpty())) - { - renderElement(g, element); - } else - { - element.doRender(g); - } - } - - private static float getTransformScale(Point2D.Float origin, Point2D.Float testPoint, - AffineTransform transform) - { - transform.transform(testPoint, testPoint); - float dx = testPoint.x - origin.x; - float dy = testPoint.y - origin.y; - return (float) Math.sqrt(dx * dx + dy * dy); - } - - private static void renderElement(Graphics2D g, RenderableElement element) throws SVGException - { - AffineTransform transform = g.getTransform(); - - Graphics2D gg = (Graphics2D) g.create(); - Rectangle elementBounds = element.getBoundingBox().getBounds(); - Rectangle transformedBounds = transform.createTransformedShape(elementBounds).getBounds(); - Rectangle dstBounds = new Rectangle(transformedBounds); - - ImageObserver observer = element.diagram.getCurrentRenderTarget(); - - Cache cache = element.getBufferCache(); - BufferedImage elementImage; - - if (cache == null || observer == null || !cache.isCompatible(transform)) - { - elementImage = renderToBuffer(gg, element, transform, transformedBounds, dstBounds); - if (observer != null) - { - // Only do caching if we are painting to a component. - Cache cacheEntry = new Cache(elementImage, new Rectangle(dstBounds), transform); - element.setBufferImage(cacheEntry); - } - } else - { - elementImage = cache.img; - dstBounds.setBounds(cache.getBoundsForTransform(transform)); - } - - // Reset the transform. We already accounted for it in the buffer image. - gg.setTransform(new AffineTransform()); - gg.drawImage(elementImage, dstBounds.x, dstBounds.y, observer); - if (DEBUG_PAINT) - { - gg.setColor(Color.GREEN); - gg.drawRect(dstBounds.x, dstBounds.y, dstBounds.width, dstBounds.height); - if (!dstBounds.equals(transformedBounds)) - { - gg.setColor(Color.PINK); - gg.drawRect(transformedBounds.x, transformedBounds.y, transformedBounds.width, transformedBounds.height); - } - } - gg.dispose(); - } - - private static BufferedImage renderToBuffer(Graphics2D gg, RenderableElement element, - AffineTransform transform, Rectangle transformedBounds, - Rectangle dstBounds) throws SVGException - { - Point2D.Float origin = new Point2D.Float(0, 0); - transform.transform(origin, origin); - - // As filter operations are commonly implemented using convolutions they need to be - // aware of any possible scaling to compensate for it in their kernel size. - Point2D.Float testPoint = new Point2D.Float(1, 0); - float xScale = getTransformScale(origin, testPoint, transform); - testPoint.setLocation(0, 1); - float yScale = getTransformScale(origin, testPoint, transform); - - List filterOps = element.filter == null - ? Collections.emptyList() - : element.filter.filterEffects.stream() - .flatMap(f -> f.getOperations(dstBounds, xScale, yScale).stream()) - .filter(Objects::nonNull) - .collect(Collectors.toList()); - - for (FilterEffects.FilterOp filterOp : filterOps) - { - int right = Math.max(dstBounds.x + dstBounds.width, - filterOp.requiredImageBounds.x + filterOp.requiredImageBounds.width); - int bottom = Math.max(dstBounds.y + dstBounds.height, - filterOp.requiredImageBounds.y + filterOp.requiredImageBounds.height); - dstBounds.x = Math.min(dstBounds.x, filterOp.requiredImageBounds.x); - dstBounds.y = Math.min(dstBounds.y, filterOp.requiredImageBounds.y); - dstBounds.width = right - dstBounds.x; - dstBounds.height = bottom - dstBounds.y; - } - - - BufferedImage elementImage = BufferPainter.paintToBuffer(gg, transform, dstBounds, transformedBounds, - element, null, true); - - for (FilterEffects.FilterOp filterOp : filterOps) - { - elementImage = filterOp.op.filter(elementImage, null); - } - - if (element.cachedMask != null) - { - // Draw the mask image. Implicitly the mask is empty i.e. has a completely black background. - // We can't draw the mask directly to the elementImage using the mask composite as - // masks may change the mask value a location at any time during mask realization. - BufferedImage maskImage = BufferPainter.paintToBuffer(gg, transform, dstBounds, transformedBounds, - element.cachedMask, Color.BLACK, false); - - Graphics2D elementGraphics = (Graphics2D) elementImage.getGraphics(); - elementGraphics.setRenderingHints(gg.getRenderingHints()); - elementGraphics.setComposite(element.cachedMask.createMaskComposite()); - elementGraphics.drawImage(maskImage, 0, 0, element.diagram.getCurrentRenderTarget()); - elementGraphics.dispose(); - } - return elementImage; - } - - public static BufferedImage paintToBuffer(Graphics2D g, AffineTransform transform, - Rectangle srcBounds, RenderableElement element, - Color bgColor) throws SVGException - { - return paintToBuffer(g, transform, srcBounds, srcBounds, element, bgColor, false); - } - - /* - * The srcBounds parameter is expected to be pre-transformed by the given transform. - */ - public static BufferedImage paintToBuffer(Graphics2D g, AffineTransform transform, - Rectangle dstBounds, Rectangle srcBounds, - RenderableElement element, - Color bgColor, boolean preMultiplied) throws SVGException - { - int type = preMultiplied - ? BufferedImage.TYPE_INT_ARGB_PRE - : BufferedImage.TYPE_INT_ARGB; - BufferedImage img = new BufferedImage(dstBounds.width, dstBounds.height, type); - Graphics2D imgGraphics = (Graphics2D) img.getGraphics(); - if (g != null) - { - imgGraphics.setRenderingHints(g.getRenderingHints()); - } else if (bgColor != null) - { - imgGraphics.setColor(bgColor); - imgGraphics.fillRect(0, 0, img.getWidth(), img.getHeight()); - } - int xRelative = srcBounds.x - dstBounds.x; - int yRelative = srcBounds.y - dstBounds.y; - imgGraphics.translate(xRelative, yRelative); - imgGraphics.clipRect(0, 0, srcBounds.width, srcBounds.height); - - // Because we blit the image at the transformed location we have to compensate for the - // element location. - imgGraphics.translate(-srcBounds.x, -srcBounds.y); - imgGraphics.transform(transform); - element.doRender(imgGraphics); - imgGraphics.dispose(); - return img; - } -} --- a/src/com/kitfox/svg/Circle.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on January 26, 2004, 5:25 PM - */ -package com.kitfox.svg; - -import com.kitfox.svg.xml.StyleAttribute; -import java.awt.Graphics2D; -import java.awt.Shape; -import java.awt.geom.Ellipse2D; -import java.awt.geom.Rectangle2D; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class Circle extends ShapeElement -{ - - public static final String TAG_NAME = "circle"; - float cx = 0f; - float cy = 0f; - float r = 0f; - Ellipse2D.Float circle = new Ellipse2D.Float(); - - /** - * Creates a new instance of Rect - */ - public Circle() - { - } - - @Override - public String getTagName() - { - return TAG_NAME; - } - - @Override - protected void build() throws SVGException - { - super.build(); - - StyleAttribute sty = new StyleAttribute(); - - if (getPres(sty.setName("cx"))) - { - cx = sty.getFloatValueWithUnits(); - } - - if (getPres(sty.setName("cy"))) - { - cy = sty.getFloatValueWithUnits(); - } - - if (getPres(sty.setName("r"))) - { - r = sty.getFloatValueWithUnits(); - } - - circle.setFrame(cx - r, cy - r, r * 2f, r * 2f); - } - - @Override - protected void doRender(Graphics2D g) throws SVGException - { - beginLayer(g); - renderShape(g, circle); - finishLayer(g); - } - - @Override - public Shape getShape() - { - return shapeToParent(circle); - } - - @Override - public Rectangle2D getBoundingBox() throws SVGException - { - return boundsToParent(includeStrokeInBounds(circle.getBounds2D())); - } - - /** - * Updates all attributes in this diagram associated with a time event. Ie, - * all attributes with track information. - * - * @return - true if this node has changed state as a result of the time - * update - */ - @Override - public boolean updateTime(double curTime) throws SVGException - { -// if (trackManager.getNumTracks() == 0) return false; - boolean changeState = super.updateTime(curTime); - - //Get current values for parameters - StyleAttribute sty = new StyleAttribute(); - boolean shapeChange = false; - - if (getPres(sty.setName("cx"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != cx) - { - cx = newVal; - shapeChange = true; - } - } - - if (getPres(sty.setName("cy"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != cy) - { - cy = newVal; - shapeChange = true; - } - } - - if (getPres(sty.setName("r"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != r) - { - r = newVal; - shapeChange = true; - } - } - - if (shapeChange) - { - build(); -// circle.setFrame(cx - r, cy - r, r * 2f, r * 2f); -// return true; - } - - return changeState || shapeChange; - } -} --- a/src/com/kitfox/svg/ClipPath.java +++ /dev/null @@ -1,174 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on January 26, 2004, 1:56 AM - */ -package com.kitfox.svg; - -import com.kitfox.svg.xml.StyleAttribute; -import java.awt.Shape; -import java.awt.geom.Area; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class ClipPath extends SVGElement -{ - - public static final String TAG_NAME = "clippath"; - public static final int CP_USER_SPACE_ON_USE = 0; - public static final int CP_OBJECT_BOUNDING_BOX = 1; - int clipPathUnits = CP_USER_SPACE_ON_USE; - - /** - * Creates a new instance of Stop - */ - public ClipPath() - { - } - - @Override - public String getTagName() - { - return TAG_NAME; - } - - /** - * Called after the start element but before the end element to indicate - * each child tag that has been processed - */ - @Override - public void loaderAddChild(SVGLoaderHelper helper, SVGElement child) throws SVGElementException - { - super.loaderAddChild(helper, child); - } - - @Override - protected void build() throws SVGException - { - super.build(); - - StyleAttribute sty = new StyleAttribute(); - - clipPathUnits = (getPres(sty.setName("clipPathUnits")) - && sty.getStringValue().equals("objectBoundingBox")) - ? CP_OBJECT_BOUNDING_BOX - : CP_USER_SPACE_ON_USE; - } - - public int getClipPathUnits() - { - return clipPathUnits; - } - - public Shape getClipPathShape() - { - if (children.isEmpty()) - { - return null; - } - if (children.size() == 1) - { - return ((ShapeElement) children.get(0)).getShape(); - } - - Area clipArea = null; - for (SVGElement svgElement : children) { - ShapeElement se = (ShapeElement) svgElement; - - if (clipArea == null) - { - Shape shape = se.getShape(); - if (shape != null) - { - clipArea = new Area(se.getShape()); - } - continue; - } - - Shape shape = se.getShape(); - if (shape != null) - { - clipArea.intersect(new Area(shape)); - } - } - - return clipArea; - } - - /** - * Updates all attributes in this diagram associated with a time event. Ie, - * all attributes with track information. - * - * @param curTime Time at which to evaluate node - * @return - true if this node has changed state as a result of the time - * update - * @throws com.kitfox.svg.SVGException - */ - @Override - public boolean updateTime(double curTime) throws SVGException - { - //Get current values for parameters - StyleAttribute sty = new StyleAttribute(); - boolean shapeChange = false; - - - if (getPres(sty.setName("clipPathUnits"))) - { - String newUnitsStrn = sty.getStringValue(); - int newUnits = newUnitsStrn.equals("objectBoundingBox") - ? CP_OBJECT_BOUNDING_BOX - : CP_USER_SPACE_ON_USE; - - if (newUnits != clipPathUnits) - { - clipPathUnits = newUnits; - shapeChange = true; - } - } - - if (shapeChange) - { - build(); - } - - for (int i = 0; i < children.size(); ++i) - { - SVGElement ele = (SVGElement) children.get(i); - ele.updateTime(curTime); - } - - return shapeChange; - } -} --- a/src/com/kitfox/svg/Defs.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on January 26, 2004, 1:56 AM - */ -package com.kitfox.svg; - -import com.kitfox.svg.xml.StyleSheet; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class Defs extends TransformableElement -{ - - public static final String TAG_NAME = "defs"; - - /** - * Creates a new instance of Stop - */ - public Defs() - { - } - - @Override - public String getTagName() - { - return TAG_NAME; - } - - /** - * Called after the start element but before the end element to indicate - * each child tag that has been processed - */ - @Override - public void loaderAddChild(SVGLoaderHelper helper, SVGElement child) throws SVGElementException - { - super.loaderAddChild(helper, child); - -// members.add(child); - } - - @Override - public boolean updateTime(double curTime) throws SVGException - { - boolean stateChange = false; - for (SVGElement ele : children) { - stateChange = stateChange || ele.updateTime(curTime); - } - - return super.updateTime(curTime) || stateChange; - } - - public StyleSheet getStyleSheet() - { - for (int i = 0; i < getNumChildren(); ++i) - { - SVGElement ele = getChild(i); - if (ele instanceof Style) - { - return ((Style)ele).getStyleSheet(); - } - } - return null; - } -} --- a/src/com/kitfox/svg/Desc.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on September 19, 2004, 1:56 AM - */ -package com.kitfox.svg; - -/** - * Holds title textual information within tree - * - * @author Mark McKay - * @author Mark McKay - */ -public class Desc extends SVGElement -{ - - public static final String TAG_NAME = "desc"; - StringBuffer text = new StringBuffer(); - - /** - * Creates a new instance of Stop - */ - public Desc() - { - } - - @Override - public String getTagName() - { - return TAG_NAME; - } - - /** - * Called during load process to add text scanned within a tag - */ - @Override - public void loaderAddText(SVGLoaderHelper helper, String text) - { - this.text.append(text); - } - - public String getText() - { - return text.toString(); - } - - @Override - public boolean updateTime(double curTime) - { - return false; - } -} --- a/src/com/kitfox/svg/Ellipse.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on January 26, 2004, 5:25 PM - */ -package com.kitfox.svg; - -import com.kitfox.svg.xml.StyleAttribute; -import java.awt.Graphics2D; -import java.awt.Shape; -import java.awt.geom.Ellipse2D; -import java.awt.geom.Rectangle2D; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class Ellipse extends ShapeElement -{ - - public static final String TAG_NAME = "ellipse"; - float cx = 0.0f; - float cy = 0.0f; - float rx = 0.0f; - float ry = 0.0f; - Ellipse2D.Float ellipse = new Ellipse2D.Float(); - - /** - * Creates a new instance of Rect - */ - public Ellipse() - { - } - - @Override - public String getTagName() - { - return TAG_NAME; - } - - @Override - protected void build() throws SVGException - { - super.build(); - - StyleAttribute sty = new StyleAttribute(); - - if (getPres(sty.setName("cx"))) - { - cx = sty.getFloatValueWithUnits(); - } - - if (getPres(sty.setName("cy"))) - { - cy = sty.getFloatValueWithUnits(); - } - - if (getPres(sty.setName("rx"))) - { - rx = sty.getFloatValueWithUnits(); - } - - if (getPres(sty.setName("ry"))) - { - ry = sty.getFloatValueWithUnits(); - } - - ellipse.setFrame(cx - rx, cy - ry, rx * 2f, ry * 2f); - } - - @Override - protected void doRender(Graphics2D g) throws SVGException - { - beginLayer(g); - renderShape(g, ellipse); - finishLayer(g); - } - - @Override - public Shape getShape() - { - return shapeToParent(ellipse); - } - - @Override - public Rectangle2D getBoundingBox() throws SVGException - { - return boundsToParent(includeStrokeInBounds(ellipse.getBounds2D())); - } - - /** - * Updates all attributes in this diagram associated with a time event. Ie, - * all attributes with track information. - * - * @return - true if this node has changed state as a result of the time - * update - */ - @Override - public boolean updateTime(double curTime) throws SVGException - { -// if (trackManager.getNumTracks() == 0) return false; - boolean changeState = super.updateTime(curTime); - - //Get current values for parameters - StyleAttribute sty = new StyleAttribute(); - boolean shapeChange = false; - - if (getPres(sty.setName("cx"))) - { - float newCx = sty.getFloatValueWithUnits(); - if (newCx != cx) - { - cx = newCx; - shapeChange = true; - } - } - - if (getPres(sty.setName("cy"))) - { - float newCy = sty.getFloatValueWithUnits(); - if (newCy != cy) - { - cy = newCy; - shapeChange = true; - } - } - - if (getPres(sty.setName("rx"))) - { - float newRx = sty.getFloatValueWithUnits(); - if (newRx != rx) - { - rx = newRx; - shapeChange = true; - } - } - - if (getPres(sty.setName("ry"))) - { - float newRy = sty.getFloatValueWithUnits(); - if (newRy != ry) - { - ry = newRy; - shapeChange = true; - } - } - - if (shapeChange) - { - build(); -// ellipse.setFrame(cx - rx, cy - ry, rx * 2f, ry * 2f); -// return true; - } - - return changeState || shapeChange; - } -} --- a/src/com/kitfox/svg/FeDistantLight.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on March 18, 2004, 6:52 AM - */ -package com.kitfox.svg; - -import com.kitfox.svg.xml.StyleAttribute; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class FeDistantLight extends FeLight -{ - - public static final String TAG_NAME = "fedistantlight"; - float azimuth = 0f; - float elevation = 0f; - - /** - * Creates a new instance of FillElement - */ - public FeDistantLight() - { - } - - @Override - public String getTagName() - { - return TAG_NAME; - } - - @Override - protected void build() throws SVGException - { - super.build(); - - StyleAttribute sty = new StyleAttribute(); - - if (getPres(sty.setName("azimuth"))) - { - azimuth = sty.getFloatValueWithUnits(); - } - - if (getPres(sty.setName("elevation"))) - { - elevation = sty.getFloatValueWithUnits(); - } - } - - public float getAzimuth() - { - return azimuth; - } - - public float getElevation() - { - return elevation; - } - - @Override - public boolean updateTime(double curTime) throws SVGException - { -// if (trackManager.getNumTracks() == 0) return false; - - //Get current values for parameters - StyleAttribute sty = new StyleAttribute(); - boolean stateChange = false; - - if (getPres(sty.setName("azimuth"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != azimuth) - { - azimuth = newVal; - stateChange = true; - } - } - - if (getPres(sty.setName("elevation"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != elevation) - { - elevation = newVal; - stateChange = true; - } - } - - return stateChange; - } -} --- a/src/com/kitfox/svg/FeGaussianBlur.java +++ /dev/null @@ -1,117 +0,0 @@ -package com.kitfox.svg; - -import com.kitfox.svg.xml.StyleAttribute; - -import java.awt.Rectangle; -import java.awt.image.ConvolveOp; -import java.awt.image.Kernel; -import java.util.Arrays; -import java.util.List; - -public class FeGaussianBlur extends FilterEffects -{ - public static final String TAG_NAME = "fegaussianblur"; - - private float[] stdDeviation; - private float xCurrent; - private float yCurrent; - private ConvolveOp xBlur; - private ConvolveOp yBlur; - - @Override - public String getTagName() - { - return TAG_NAME; - } - - @Override - protected void build() throws SVGException - { - super.build(); - StyleAttribute sty = new StyleAttribute(); - - stdDeviation = new float[]{0f}; - if (getPres(sty.setName("stdDeviation"))) - { - stdDeviation = sty.getFloatList(); - } - xBlur = null; - yBlur = null; - } - - @Override - public List getOperations(Rectangle inputBounds, float xScale, float yScale) - { - float xSigma = xScale * stdDeviation[0]; - float ySigma = yScale * stdDeviation[Math.min(stdDeviation.length - 1, 1)]; - - return Arrays.asList( - xSigma > 0 - ? getGaussianBlurFilter(inputBounds, xSigma, true) - : null, - ySigma > 0 - ? getGaussianBlurFilter(inputBounds, ySigma, false) - : null - ); - } - - public FilterOp getGaussianBlurFilter(Rectangle inputBounds, float sigma, boolean horizontal) - { - int multiplier = 2; - float radius = 2f * sigma + 1; - int size = (int) Math.ceil(radius * multiplier) + 1; - if (horizontal && (xBlur == null || xCurrent != sigma) - || !horizontal && (yBlur == null || yCurrent != sigma)) - { - if (horizontal) - { - xCurrent = sigma; - } else - { - yCurrent = sigma; - } - float[] data = new float[size]; - - float radius2 = radius * radius; - float twoSigmaSquare = 2.0f * sigma * sigma; - float sigmaRoot = (float) Math.sqrt(twoSigmaSquare * Math.PI); - float total = 0.0f; - - float middle = size / 2f; - for (int i = 0; i < size; i++) - { - float distance = middle - i; - distance *= distance; - - data[i] = distance > radius2 - ? 0 - : (float) Math.exp(-distance / twoSigmaSquare) / sigmaRoot; - total += data[i]; - } - - for (int i = 0; i < data.length; i++) - { - data[i] /= total; - } - - if (horizontal) - { - xBlur = new ConvolveOp(new Kernel(size, 1, data), ConvolveOp.EDGE_NO_OP, null); - } else - { - yBlur = new ConvolveOp(new Kernel(1, size, data), ConvolveOp.EDGE_NO_OP, null); - } - } - - Rectangle dstBounds = new Rectangle(inputBounds); - if (horizontal) - { - dstBounds.grow(size, 0); - } else - { - dstBounds.grow(0, size); - } - - return new FilterOp(horizontal ? xBlur : yBlur, dstBounds); - } -} --- a/src/com/kitfox/svg/FeLight.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on March 18, 2004, 6:52 AM - */ -package com.kitfox.svg; - -/** - * @author Mark McKay - * @author Mark McKay - */ -abstract public class FeLight extends FilterEffects -{ - - public static final String TAG_NAME = "feLight"; - - /** - * Creates a new instance of FillElement - */ - public FeLight() - { - } - - @Override - public String getTagName() - { - return TAG_NAME; - } -} --- a/src/com/kitfox/svg/FePointLight.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on March 18, 2004, 6:52 AM - */ -package com.kitfox.svg; - -import com.kitfox.svg.xml.StyleAttribute; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class FePointLight extends FeLight -{ - - public static final String TAG_NAME = "fepointlight"; - float x = 0f; - float y = 0f; - float z = 0f; - - /** - * Creates a new instance of FillElement - */ - public FePointLight() - { - } - - @Override - public String getTagName() - { - return TAG_NAME; - } - - @Override - protected void build() throws SVGException - { - super.build(); - - StyleAttribute sty = new StyleAttribute(); - - if (getPres(sty.setName("x"))) - { - x = sty.getFloatValueWithUnits(); - } - - if (getPres(sty.setName("y"))) - { - y = sty.getFloatValueWithUnits(); - } - - if (getPres(sty.setName("z"))) - { - z = sty.getFloatValueWithUnits(); - } - } - - @Override - public float getX() - { - return x; - } - - @Override - public float getY() - { - return y; - } - - public float getZ() - { - return z; - } - - @Override - public boolean updateTime(double curTime) throws SVGException - { -// if (trackManager.getNumTracks() == 0) return false; - - //Get current values for parameters - StyleAttribute sty = new StyleAttribute(); - boolean stateChange = false; - - if (getPres(sty.setName("x"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != x) - { - x = newVal; - stateChange = true; - } - } - - if (getPres(sty.setName("y"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != y) - { - y = newVal; - stateChange = true; - } - } - - if (getPres(sty.setName("z"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != z) - { - z = newVal; - stateChange = true; - } - } - - return stateChange; - } -} --- a/src/com/kitfox/svg/FeSpotLight.java +++ /dev/null @@ -1,244 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on March 18, 2004, 6:52 AM - */ -package com.kitfox.svg; - -import com.kitfox.svg.xml.StyleAttribute; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class FeSpotLight extends FeLight -{ - - public static final String TAG_NAME = "fespotlight"; - float x = 0f; - float y = 0f; - float z = 0f; - float pointsAtX = 0f; - float pointsAtY = 0f; - float pointsAtZ = 0f; - float specularComponent = 0f; - float limitingConeAngle = 0f; - - /** - * Creates a new instance of FillElement - */ - public FeSpotLight() - { - } - - @Override - public String getTagName() - { - return TAG_NAME; - } - - @Override - protected void build() throws SVGException - { - super.build(); - - StyleAttribute sty = new StyleAttribute(); - - if (getPres(sty.setName("x"))) - { - x = sty.getFloatValueWithUnits(); - } - if (getPres(sty.setName("y"))) - { - y = sty.getFloatValueWithUnits(); - } - if (getPres(sty.setName("z"))) - { - z = sty.getFloatValueWithUnits(); - } - if (getPres(sty.setName("pointsAtX"))) - { - pointsAtX = sty.getFloatValueWithUnits(); - } - if (getPres(sty.setName("pointsAtY"))) - { - pointsAtY = sty.getFloatValueWithUnits(); - } - if (getPres(sty.setName("pointsAtZ"))) - { - pointsAtZ = sty.getFloatValueWithUnits(); - } - if (getPres(sty.setName("specularComponent"))) - { - specularComponent = sty.getFloatValueWithUnits(); - } - if (getPres(sty.setName("limitingConeAngle"))) - { - limitingConeAngle = sty.getFloatValueWithUnits(); - } - } - - @Override - public float getX() - { - return x; - } - - @Override - public float getY() - { - return y; - } - - public float getZ() - { - return z; - } - - public float getPointsAtX() - { - return pointsAtX; - } - - public float getPointsAtY() - { - return pointsAtY; - } - - public float getPointsAtZ() - { - return pointsAtZ; - } - - public float getSpecularComponent() - { - return specularComponent; - } - - public float getLimitingConeAngle() - { - return limitingConeAngle; - } - - @Override - public boolean updateTime(double curTime) throws SVGException - { -// if (trackManager.getNumTracks() == 0) return false; - - //Get current values for parameters - StyleAttribute sty = new StyleAttribute(); - boolean stateChange = false; - - if (getPres(sty.setName("x"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != x) - { - x = newVal; - stateChange = true; - } - } - - if (getPres(sty.setName("y"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != y) - { - y = newVal; - stateChange = true; - } - } - - if (getPres(sty.setName("z"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != z) - { - z = newVal; - stateChange = true; - } - } - - if (getPres(sty.setName("pointsAtX"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != pointsAtX) - { - pointsAtX = newVal; - stateChange = true; - } - } - - if (getPres(sty.setName("pointsAtY"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != pointsAtY) - { - pointsAtY = newVal; - stateChange = true; - } - } - - if (getPres(sty.setName("pointsAtZ"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != pointsAtZ) - { - pointsAtZ = newVal; - stateChange = true; - } - } - - if (getPres(sty.setName("specularComponent"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != specularComponent) - { - specularComponent = newVal; - stateChange = true; - } - } - - if (getPres(sty.setName("limitingConeAngle"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != limitingConeAngle) - { - limitingConeAngle = newVal; - stateChange = true; - } - } - - return stateChange; - } -} --- a/src/com/kitfox/svg/FillElement.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on March 18, 2004, 6:52 AM - */ -package com.kitfox.svg; - -import java.awt.*; -import java.awt.geom.*; - -/** - * @author Mark McKay - * @author Mark McKay - */ -abstract public class FillElement extends SVGElement -{ - /** - * Creates a new instance of FillElement - */ - public FillElement() - { - } - - /** - * Requests the paint defined by this element. Passes in information to - * allow paint to be customized - * - * @param bounds - bounding box of shape being rendered - * @param xform - The current transformation that the shape is being - * rendered under. - * @return paint object - */ - abstract public Paint getPaint(Rectangle2D bounds, AffineTransform xform); -} --- a/src/com/kitfox/svg/Filter.java +++ /dev/null @@ -1,287 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on March 18, 2004, 6:52 AM - */ -package com.kitfox.svg; - -import com.kitfox.svg.xml.StyleAttribute; -import java.awt.geom.Point2D; -import java.net.URI; -import java.net.URL; -import java.util.ArrayList; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class Filter extends SVGElement -{ - - public static final String TAG_NAME = "filter"; - public static final int FU_OBJECT_BOUNDING_BOX = 0; - public static final int FU_USER_SPACE_ON_USE = 1; - protected int filterUnits = FU_OBJECT_BOUNDING_BOX; - public static final int PU_OBJECT_BOUNDING_BOX = 0; - public static final int PU_USER_SPACE_ON_USE = 1; - protected int primitiveUnits = PU_OBJECT_BOUNDING_BOX; - float x = 0f; - float y = 0f; - float width = 1f; - float height = 1f; - Point2D filterRes = new Point2D.Double(); - URL href = null; - final ArrayList filterEffects = new ArrayList<>(); - - /** - * Creates a new instance of FillElement - */ - public Filter() - { - } - - @Override - public String getTagName() - { - return TAG_NAME; - } - - /** - * Called after the start element but before the end element to indicate - * each child tag that has been processed - */ - @Override - public void loaderAddChild(SVGLoaderHelper helper, SVGElement child) throws SVGElementException - { - super.loaderAddChild(helper, child); - - if (child instanceof FilterEffects) - { - filterEffects.add((FilterEffects) child); - } - } - - @Override - protected void build() throws SVGException - { - super.build(); - - StyleAttribute sty = new StyleAttribute(); - String strn; - - if (getPres(sty.setName("filterUnits"))) - { - strn = sty.getStringValue().toLowerCase(); - if (strn.equals("userspaceonuse")) - { - filterUnits = FU_USER_SPACE_ON_USE; - } else - { - filterUnits = FU_OBJECT_BOUNDING_BOX; - } - } - - if (getPres(sty.setName("primitiveUnits"))) - { - strn = sty.getStringValue().toLowerCase(); - if (strn.equals("userspaceonuse")) - { - primitiveUnits = PU_USER_SPACE_ON_USE; - } else - { - primitiveUnits = PU_OBJECT_BOUNDING_BOX; - } - } - - if (getPres(sty.setName("x"))) - { - x = sty.getFloatValueWithUnits(); - } - - if (getPres(sty.setName("y"))) - { - y = sty.getFloatValueWithUnits(); - } - - if (getPres(sty.setName("width"))) - { - width = sty.getFloatValueWithUnits(); - } - - if (getPres(sty.setName("height"))) - { - height = sty.getFloatValueWithUnits(); - } - - try - { - if (getPres(sty.setName("xlink:href"))) - { - URI src = sty.getURIValue(getXMLBase()); - href = src.toURL(); - } - } catch (Exception e) - { - throw new SVGException(e); - } - - } - - public float getX() - { - return x; - } - - public float getY() - { - return y; - } - - public float getWidth() - { - return width; - } - - public float getHeight() - { - return height; - } - - @Override - public boolean updateTime(double curTime) throws SVGException - { -// if (trackManager.getNumTracks() == 0) return false; - - //Get current values for parameters - StyleAttribute sty = new StyleAttribute(); - boolean stateChange = false; - - if (getPres(sty.setName("x"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != x) - { - x = newVal; - stateChange = true; - } - } - - if (getPres(sty.setName("y"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != y) - { - y = newVal; - stateChange = true; - } - } - - if (getPres(sty.setName("width"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != width) - { - width = newVal; - stateChange = true; - } - } - - if (getPres(sty.setName("height"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != height) - { - height = newVal; - stateChange = true; - } - } - - try - { - if (getPres(sty.setName("xlink:href"))) - { - URI src = sty.getURIValue(getXMLBase()); - URL newVal = src.toURL(); - - if (!newVal.equals(href)) - { - href = newVal; - stateChange = true; - } - } - } catch (Exception e) - { - throw new SVGException(e); - } - - if (getPres(sty.setName("filterUnits"))) - { - int newVal; - String strn = sty.getStringValue().toLowerCase(); - if (strn.equals("userspaceonuse")) - { - newVal = FU_USER_SPACE_ON_USE; - } else - { - newVal = FU_OBJECT_BOUNDING_BOX; - } - if (newVal != filterUnits) - { - filterUnits = newVal; - stateChange = true; - } - } - - if (getPres(sty.setName("primitiveUnits"))) - { - int newVal; - String strn = sty.getStringValue().toLowerCase(); - if (strn.equals("userspaceonuse")) - { - newVal = PU_USER_SPACE_ON_USE; - } else - { - newVal = PU_OBJECT_BOUNDING_BOX; - } - if (newVal != filterUnits) - { - primitiveUnits = newVal; - stateChange = true; - } - } - - - - return stateChange; - } -} --- a/src/com/kitfox/svg/FilterEffects.java +++ /dev/null @@ -1,273 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on March 18, 2004, 6:52 AM - */ -package com.kitfox.svg; - -import com.kitfox.svg.xml.StyleAttribute; - -import java.awt.Rectangle; -import java.awt.image.BufferedImageOp; -import java.net.URI; -import java.net.URL; -import java.util.List; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public abstract class FilterEffects extends SVGElement -{ - public static final String TAG_NAME = "filtereffects"; - - public static final int FP_SOURCE_GRAPHIC = 0; - public static final int FP_SOURCE_ALPHA = 1; - public static final int FP_BACKGROUND_IMAGE = 2; - public static final int FP_BACKGROUND_ALPHA = 3; - public static final int FP_FILL_PAINT = 4; - public static final int FP_STROKE_PAINT = 5; - public static final int FP_CUSTOM = 5; - private int filterPrimitiveTypeIn; - private String filterPrimitiveRefIn; - float x = 0f; - float y = 0f; - float width = 1f; - float height = 1f; - URL href = null; - - /** - * Creates a new instance of FillElement - */ - public FilterEffects() - { - } - - @Override - public String getTagName() - { - return TAG_NAME; - } - - /** - * Called after the start element but before the end element to indicate - * each child tag that has been processed - */ - @Override - public void loaderAddChild(SVGLoaderHelper helper, SVGElement child) throws SVGElementException - { - super.loaderAddChild(helper, child); - - if (child instanceof FilterEffects) - { -// filterEffects.add(child); - } - } - - @Override - protected void build() throws SVGException - { - super.build(); - - /*StyleAttribute sty = new StyleAttribute(); - String strn; - - if (getPres(sty.setName("filterUnits"))) - { - strn = sty.getStringValue().toLowerCase(); - if (strn.equals("userspaceonuse")) filterUnits = FU_USER_SPACE_ON_USE; - else filterUnits = FU_OBJECT_BOUNDING_BOX; - } - - if (getPres(sty.setName("primitiveUnits"))) - { - strn = sty.getStringValue().toLowerCase(); - if (strn.equals("userspaceonuse")) primitiveUnits = PU_USER_SPACE_ON_USE; - else primitiveUnits = PU_OBJECT_BOUNDING_BOX; - } - - if (getPres(sty.setName("x"))) x = sty.getFloatValue(); - - if (getPres(sty.setName("y"))) y = sty.getFloatValue(); - - if (getPres(sty.setName("width"))) width = sty.getFloatValue(); - - if (getPres(sty.setName("height"))) height = sty.getFloatValue(); - - try { - if (getPres(sty.setName("xlink:href"))) - { - URI src = sty.getURIValue(getXMLBase()); - href = src.toURL(); - } - } - catch (Exception e) - { - throw new SVGException(e); - } - */ - } - - public List getOperations(Rectangle bounds, float xScale, float yScale) { - return null; - } - - public float getX() - { - return x; - } - - public float getY() - { - return y; - } - - public float getWidth() - { - return width; - } - - public float getHeight() - { - return height; - } - - @Override - public boolean updateTime(double curTime) throws SVGException - { -// if (trackManager.getNumTracks() == 0) return false; - - //Get current values for parameters - StyleAttribute sty = new StyleAttribute(); - boolean stateChange = false; - - if (getPres(sty.setName("x"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != x) - { - x = newVal; - stateChange = true; - } - } - - if (getPres(sty.setName("y"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != y) - { - y = newVal; - stateChange = true; - } - } - - if (getPres(sty.setName("width"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != width) - { - width = newVal; - stateChange = true; - } - } - - if (getPres(sty.setName("height"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != height) - { - height = newVal; - stateChange = true; - } - } - - try - { - if (getPres(sty.setName("xlink:href"))) - { - URI src = sty.getURIValue(getXMLBase()); - URL newVal = src.toURL(); - - if (!newVal.equals(href)) - { - href = newVal; - stateChange = true; - } - } - } catch (Exception e) - { - throw new SVGException(e); - } - - /* - if (getPres(sty.setName("filterUnits"))) - { - int newVal; - String strn = sty.getStringValue().toLowerCase(); - if (strn.equals("userspaceonuse")) newVal = FU_USER_SPACE_ON_USE; - else newVal = FU_OBJECT_BOUNDING_BOX; - if (newVal != filterUnits) - { - filterUnits = newVal; - stateChange = true; - } - } - - if (getPres(sty.setName("primitiveUnits"))) - { - int newVal; - String strn = sty.getStringValue().toLowerCase(); - if (strn.equals("userspaceonuse")) newVal = PU_USER_SPACE_ON_USE; - else newVal = PU_OBJECT_BOUNDING_BOX; - if (newVal != filterUnits) - { - primitiveUnits = newVal; - stateChange = true; - } - } - - */ - - return stateChange; - } - - public static class FilterOp { - public final BufferedImageOp op; - public final Rectangle requiredImageBounds; - - public FilterOp(BufferedImageOp op, Rectangle requiredImageBounds) { - this.op = op; - this.requiredImageBounds = requiredImageBounds; - } - } -} --- a/src/com/kitfox/svg/Font.java +++ /dev/null @@ -1,292 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on February 20, 2004, 10:00 PM - */ -package com.kitfox.svg; - -import com.kitfox.svg.xml.StyleAttribute; -import java.util.HashMap; - -/** - * Implements an embedded font. - * - * SVG specification: http://www.w3.org/TR/SVG/fonts.html - * - * @author Mark McKay - * @author Mark McKay - */ -public class Font extends SVGElement -{ - - public static final String TAG_NAME = "font"; - int horizOriginX = 0; - int horizOriginY = 0; - int horizAdvX = -1; //Must be specified - int vertOriginX = -1; //Defaults to horizAdvX / 2 - int vertOriginY = -1; //Defaults to font's ascent - int vertAdvY = -1; //Defaults to one 'em'. See font-face - FontFace fontFace = null; - MissingGlyph missingGlyph = null; - final HashMap glyphs = new HashMap(); - - /** - * Creates a new instance of Font - */ - public Font() - { - } - - @Override - public String getTagName() - { - return TAG_NAME; - } - - /** - * Called after the start element but before the end element to indicate - * each child tag that has been processed - */ - @Override - public void loaderAddChild(SVGLoaderHelper helper, SVGElement child) throws SVGElementException - { - super.loaderAddChild(helper, child); - - if (child instanceof Glyph) - { - glyphs.put(((Glyph) child).getUnicode(), child); - } else if (child instanceof MissingGlyph) - { - missingGlyph = (MissingGlyph) child; - } else if (child instanceof FontFace) - { - fontFace = (FontFace) child; - } - } - - @Override - public void loaderEndElement(SVGLoaderHelper helper) throws SVGParseException - { - super.loaderEndElement(helper); - - //build(); - - helper.universe.registerFont(this); - } - - @Override - protected void build() throws SVGException - { - super.build(); - - StyleAttribute sty = new StyleAttribute(); - - if (getPres(sty.setName("horiz-origin-x"))) - { - horizOriginX = sty.getIntValue(); - } - - if (getPres(sty.setName("horiz-origin-y"))) - { - horizOriginY = sty.getIntValue(); - } - - if (getPres(sty.setName("horiz-adv-x"))) - { - horizAdvX = sty.getIntValue(); - } - - if (getPres(sty.setName("vert-origin-x"))) - { - vertOriginX = sty.getIntValue(); - } - - if (getPres(sty.setName("vert-origin-y"))) - { - vertOriginY = sty.getIntValue(); - } - - if (getPres(sty.setName("vert-adv-y"))) - { - vertAdvY = sty.getIntValue(); - } - } - - public FontFace getFontFace() - { - return fontFace; - } - - public void setFontFace(FontFace face) - { - fontFace = face; - } - - public MissingGlyph getGlyph(String unicode) - { - Glyph retVal = (Glyph) glyphs.get(unicode); - if (retVal == null) - { - return missingGlyph; - } - return retVal; - } - - public int getHorizOriginX() - { - return horizOriginX; - } - - public int getHorizOriginY() - { - return horizOriginY; - } - - public int getHorizAdvX() - { - return horizAdvX; - } - - public int getVertOriginX() - { - if (vertOriginX != -1) - { - return vertOriginX; - } - vertOriginX = getHorizAdvX() / 2; - return vertOriginX; - } - - public int getVertOriginY() - { - if (vertOriginY != -1) - { - return vertOriginY; - } - vertOriginY = fontFace.getAscent(); - return vertOriginY; - } - - public int getVertAdvY() - { - if (vertAdvY != -1) - { - return vertAdvY; - } - vertAdvY = fontFace.getUnitsPerEm(); - return vertAdvY; - } - - /** - * Updates all attributes in this diagram associated with a time event. Ie, - * all attributes with track information. - * - * @return - true if this node has changed state as a result of the time - * update - */ - @Override - public boolean updateTime(double curTime) throws SVGException - { - //Fonts can't change - return false; - /* - if (trackManager.getNumTracks() == 0) return false; - - //Get current values for parameters - StyleAttribute sty = new StyleAttribute(); - boolean stateChange = false; - - if (getPres(sty.setName("horiz-origin-x"))) - { - int newVal = sty.getIntValue(); - if (newVal != horizOriginX) - { - horizOriginX = newVal; - stateChange = true; - } - } - - if (getPres(sty.setName("horiz-origin-y"))) - { - int newVal = sty.getIntValue(); - if (newVal != horizOriginY) - { - horizOriginY = newVal; - stateChange = true; - } - } - - if (getPres(sty.setName("horiz-adv-x"))) - { - int newVal = sty.getIntValue(); - if (newVal != horizAdvX) - { - horizAdvX = newVal; - stateChange = true; - } - } - - if (getPres(sty.setName("vert-origin-x"))) - { - int newVal = sty.getIntValue(); - if (newVal != vertOriginX) - { - vertOriginX = newVal; - stateChange = true; - } - } - - if (getPres(sty.setName("vert-origin-y"))) - { - int newVal = sty.getIntValue(); - if (newVal != vertOriginY) - { - vertOriginY = newVal; - stateChange = true; - } - } - - if (getPres(sty.setName("vert-adv-y"))) - { - int newVal = sty.getIntValue(); - if (newVal != vertAdvY) - { - vertAdvY = newVal; - stateChange = true; - } - } - - return shapeChange; - */ - } -} --- a/src/com/kitfox/svg/FontFace.java +++ /dev/null @@ -1,319 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on February 20, 2004, 10:00 PM - */ -package com.kitfox.svg; - -import com.kitfox.svg.xml.StyleAttribute; - -/** - * Implements an embedded font. - * - * SVG specification: http://www.w3.org/TR/SVG/fonts.html - * - * @author Mark McKay - * @author Mark McKay - */ -public class FontFace extends SVGElement -{ - - public static final String TAG_NAME = "fontface"; - String fontFamily; - /** - * Em size of coordinate system font is defined in - */ - private int unitsPerEm = 1000; - private int ascent = -1; - private int descent = -1; - private int accentHeight = -1; - private int underlinePosition = -1; - private int underlineThickness = -1; - private int strikethroughPosition = -1; - private int strikethroughThickness = -1; - private int overlinePosition = -1; - private int overlineThickness = -1; - - /** - * Creates a new instance of Font - */ - public FontFace() - { - } - - @Override - public String getTagName() - { - return TAG_NAME; - } - - @Override - protected void build() throws SVGException - { - super.build(); - - StyleAttribute sty = new StyleAttribute(); - - if (getPres(sty.setName("font-family"))) - { - fontFamily = sty.getStringValue(); - } - - if (getPres(sty.setName("units-per-em"))) - { - unitsPerEm = sty.getIntValue(); - } - if (getPres(sty.setName("ascent"))) - { - ascent = sty.getIntValue(); - } - if (getPres(sty.setName("descent"))) - { - descent = sty.getIntValue(); - } - if (getPres(sty.setName("accent-height"))) - { - accentHeight = sty.getIntValue(); - } - - if (getPres(sty.setName("underline-position"))) - { - underlinePosition = sty.getIntValue(); - } - if (getPres(sty.setName("underline-thickness"))) - { - underlineThickness = sty.getIntValue(); - } - if (getPres(sty.setName("strikethrough-position"))) - { - strikethroughPosition = sty.getIntValue(); - } - if (getPres(sty.setName("strikethrough-thickenss"))) - { - strikethroughThickness = sty.getIntValue(); - } - if (getPres(sty.setName("overline-position"))) - { - overlinePosition = sty.getIntValue(); - } - if (getPres(sty.setName("overline-thickness"))) - { - overlineThickness = sty.getIntValue(); - } - } - - public String getFontFamily() - { - return fontFamily; - } - - public int getUnitsPerEm() - { - return unitsPerEm; - } - - public int getAscent() - { - if (ascent == -1) - { - ascent = unitsPerEm - ((Font) parent).getVertOriginY(); - } - return ascent; - } - - public int getDescent() - { - if (descent == -1) - { - descent = ((Font) parent).getVertOriginY(); - } - return descent; - } - - public int getAccentHeight() - { - if (accentHeight == -1) - { - accentHeight = getAscent(); - } - return accentHeight; - } - - public int getUnderlinePosition() - { - if (underlinePosition == -1) - { - underlinePosition = unitsPerEm * 5 / 6; - } - return underlinePosition; - } - - public int getUnderlineThickness() - { - if (underlineThickness == -1) - { - underlineThickness = unitsPerEm / 20; - } - return underlineThickness; - } - - public int getStrikethroughPosition() - { - if (strikethroughPosition == -1) - { - strikethroughPosition = unitsPerEm * 3 / 6; - } - return strikethroughPosition; - } - - public int getStrikethroughThickness() - { - if (strikethroughThickness == -1) - { - strikethroughThickness = unitsPerEm / 20; - } - return strikethroughThickness; - } - - public int getOverlinePosition() - { - if (overlinePosition == -1) - { - overlinePosition = unitsPerEm * 5 / 6; - } - return overlinePosition; - } - - public int getOverlineThickness() - { - if (overlineThickness == -1) - { - overlineThickness = unitsPerEm / 20; - } - return overlineThickness; - } - - /** - * Updates all attributes in this diagram associated with a time event. Ie, - * all attributes with track information. - * - * @return - true if this node has changed state as a result of the time - * update - */ - @Override - public boolean updateTime(double curTime) - { - //Fonts can't change - return false; - } - - /** - * @param unitsPerEm the unitsPerEm to set - */ - public void setUnitsPerEm(int unitsPerEm) - { - this.unitsPerEm = unitsPerEm; - } - - /** - * @param ascent the ascent to set - */ - public void setAscent(int ascent) - { - this.ascent = ascent; - } - - /** - * @param descent the descent to set - */ - public void setDescent(int descent) - { - this.descent = descent; - } - - /** - * @param accentHeight the accentHeight to set - */ - public void setAccentHeight(int accentHeight) - { - this.accentHeight = accentHeight; - } - - /** - * @param underlinePosition the underlinePosition to set - */ - public void setUnderlinePosition(int underlinePosition) - { - this.underlinePosition = underlinePosition; - } - - /** - * @param underlineThickness the underlineThickness to set - */ - public void setUnderlineThickness(int underlineThickness) - { - this.underlineThickness = underlineThickness; - } - - /** - * @param strikethroughPosition the strikethroughPosition to set - */ - public void setStrikethroughPosition(int strikethroughPosition) - { - this.strikethroughPosition = strikethroughPosition; - } - - /** - * @param strikethroughThickness the strikethroughThickness to set - */ - public void setStrikethroughThickness(int strikethroughThickness) - { - this.strikethroughThickness = strikethroughThickness; - } - - /** - * @param overlinePosition the overlinePosition to set - */ - public void setOverlinePosition(int overlinePosition) - { - this.overlinePosition = overlinePosition; - } - - /** - * @param overlineThickness the overlineThickness to set - */ - public void setOverlineThickness(int overlineThickness) - { - this.overlineThickness = overlineThickness; - } -} --- a/src/com/kitfox/svg/Glyph.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on February 20, 2004, 10:00 PM - */ -package com.kitfox.svg; - -import com.kitfox.svg.xml.StyleAttribute; - -/** - * Implements an embedded font. - * - * SVG specification: http://www.w3.org/TR/SVG/fonts.html - * - * @author Mark McKay - * @author Mark McKay - */ -public class Glyph extends MissingGlyph -{ - - public static final String TAG_NAME = "missingglyph"; - /** - * One or more characters indicating the unicode sequence that denotes this - * glyph. - */ - String unicode; - - /** - * Creates a new instance of Font - */ - public Glyph() - { - } - - @Override - public String getTagName() - { - return TAG_NAME; - } - - @Override - protected void build() throws SVGException - { - super.build(); - - StyleAttribute sty = new StyleAttribute(); - - if (getPres(sty.setName("unicode"))) - { - unicode = sty.getStringValue(); - } - } - - public String getUnicode() - { - return unicode; - } - - /** - * Updates all attributes in this diagram associated with a time event. Ie, - * all attributes with track information. - * - * @return - true if this node has changed state as a result of the time - * update - */ - @Override - public boolean updateTime(double curTime) throws SVGException - { - //Fonts can't change - return false; - } -} --- a/src/com/kitfox/svg/Gradient.java +++ /dev/null @@ -1,368 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on January 26, 2004, 3:25 AM - */ -package com.kitfox.svg; - -import com.kitfox.svg.xml.StyleAttribute; -import java.awt.Color; -import java.awt.geom.AffineTransform; -import java.net.URI; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.Iterator; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * @author Mark McKay - * @author Mark McKay - */ -abstract public class Gradient extends FillElement -{ - public static final String TAG_NAME = "gradient"; - - public static final int SM_PAD = 0; - public static final int SM_REPEAT = 1; - public static final int SM_REFLECT = 2; - int spreadMethod = SM_PAD; - public static final int GU_OBJECT_BOUNDING_BOX = 0; - public static final int GU_USER_SPACE_ON_USE = 1; - protected int gradientUnits = GU_OBJECT_BOUNDING_BOX; - //Either this gradient contains a list of stops, or it will take it's - // stops from the referenced gradient - ArrayList stops = new ArrayList(); - URI stopRef = null; - protected AffineTransform gradientTransform = null; - - //Cache arrays of stop values here - float[] stopFractions; - Color[] stopColors; - - /** - * Creates a new instance of Gradient - */ - public Gradient() - { - } - - @Override - public String getTagName() - { - return TAG_NAME; - } - - /** - * Called after the start element but before the end element to indicate - * each child tag that has been processed - */ - @Override - public void loaderAddChild(SVGLoaderHelper helper, SVGElement child) throws SVGElementException - { - super.loaderAddChild(helper, child); - - if (!(child instanceof Stop)) - { - return; - } - appendStop((Stop) child); - } - - @Override - protected void build() throws SVGException - { - super.build(); - - StyleAttribute sty = new StyleAttribute(); - String strn; - - if (getPres(sty.setName("spreadMethod"))) - { - strn = sty.getStringValue().toLowerCase(); - if (strn.equals("repeat")) - { - spreadMethod = SM_REPEAT; - } else if (strn.equals("reflect")) - { - spreadMethod = SM_REFLECT; - } else - { - spreadMethod = SM_PAD; - } - } - - if (getPres(sty.setName("gradientUnits"))) - { - strn = sty.getStringValue().toLowerCase(); - if (strn.equals("userspaceonuse")) - { - gradientUnits = GU_USER_SPACE_ON_USE; - } else - { - gradientUnits = GU_OBJECT_BOUNDING_BOX; - } - } - - if (getPres(sty.setName("gradientTransform"))) - { - gradientTransform = parseTransform(sty.getStringValue()); - } - //If we still don't have one, set it to identity - if (gradientTransform == null) - { - gradientTransform = new AffineTransform(); - } - - - //Check to see if we're using our own stops or referencing someone else's - if (getPres(sty.setName("xlink:href"))) - { - try - { - stopRef = sty.getURIValue(getXMLBase()); -//System.err.println("Gradient: " + sty.getStringValue() + ", " + getXMLBase() + ", " + src); -// URI src = getXMLBase().resolve(href); -// stopRef = (Gradient)diagram.getUniverse().getElement(src); - } catch (Exception e) - { - throw new SVGException("Could not resolve relative URL in Gradient: " + sty.getStringValue() + ", " + getXMLBase(), e); - } - } - } - - private void buildStops() - { - ArrayList stopList = new ArrayList(stops); - stopList.sort(new Comparator(){ - public int compare(Stop o1, Stop o2) - { - return Float.compare(o1.offset, o2.offset); - } - }); - - //Remove doubles - for (int i = stopList.size() - 2; i >= 0; --i) - { - if (stopList.get(i + 1).offset == stopList.get(i).offset) - { - stopList.remove(i + 1); - } - } - - - stopFractions = new float[stopList.size()]; - stopColors = new Color[stopList.size()]; - int idx = 0; - for (Stop stop : stopList) - { - int stopColorVal = stop.color.getRGB(); - Color stopColor = new Color((stopColorVal >> 16) & 0xff, (stopColorVal >> 8) & 0xff, stopColorVal & 0xff, clamp((int) (stop.opacity * 255), 0, 255)); - - stopColors[idx] = stopColor; - stopFractions[idx] = stop.offset; - idx++; - } - - } - - public float[] getStopFractions() - { - if (stopRef != null) - { - Gradient grad = (Gradient) diagram.getUniverse().getElement(stopRef); - return grad.getStopFractions(); - } - - if (stopFractions != null) - { - return stopFractions; - } - - buildStops(); - - return stopFractions; - } - - public Color[] getStopColors() - { - if (stopRef != null) - { - Gradient grad = (Gradient) diagram.getUniverse().getElement(stopRef); - return grad.getStopColors(); - } - - if (stopColors != null) - { - return stopColors; - } - - buildStops(); - - return stopColors; - } - -// public void setStops(Color[] colors, float[] fractions) -// { -// if (colors.length != fractions.length) -// { -// throw new IllegalArgumentException(); -// } -// -// this.stopColors = colors; -// this.stopFractions = fractions; -// stopRef = null; -// } - - private int clamp(int val, int min, int max) - { - if (val < min) - { - return min; - } - if (val > max) - { - return max; - } - return val; - } - - public void setStopRef(URI grad) - { - stopRef = grad; - } - - public void appendStop(Stop stop) - { - stops.add(stop); - } - - /** - * Updates all attributes in this diagram associated with a time event. Ie, - * all attributes with track information. - * - * @return - true if this node has changed state as a result of the time - * update - */ - @Override - public boolean updateTime(double curTime) throws SVGException - { -// if (trackManager.getNumTracks() == 0) return false; - boolean stateChange = false; - - //Get current values for parameters - StyleAttribute sty = new StyleAttribute(); - String strn; - - - if (getPres(sty.setName("spreadMethod"))) - { - int newVal; - strn = sty.getStringValue().toLowerCase(); - if (strn.equals("repeat")) - { - newVal = SM_REPEAT; - } else if (strn.equals("reflect")) - { - newVal = SM_REFLECT; - } else - { - newVal = SM_PAD; - } - if (spreadMethod != newVal) - { - spreadMethod = newVal; - stateChange = true; - } - } - - if (getPres(sty.setName("gradientUnits"))) - { - int newVal; - strn = sty.getStringValue().toLowerCase(); - if (strn.equals("userspaceonuse")) - { - newVal = GU_USER_SPACE_ON_USE; - } else - { - newVal = GU_OBJECT_BOUNDING_BOX; - } - if (newVal != gradientUnits) - { - gradientUnits = newVal; - stateChange = true; - } - } - - if (getPres(sty.setName("gradientTransform"))) - { - AffineTransform newVal = parseTransform(sty.getStringValue()); - if (newVal != null && newVal.equals(gradientTransform)) - { - gradientTransform = newVal; - stateChange = true; - } - } - - - //Check to see if we're using our own stops or referencing someone else's - if (getPres(sty.setName("xlink:href"))) - { - try - { - URI newVal = sty.getURIValue(getXMLBase()); - if ((newVal == null && stopRef != null) || !newVal.equals(stopRef)) - { - stopRef = newVal; - stateChange = true; - } - } catch (Exception e) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, - "Could not parse xlink:href", e); - } - } - - //Check stops, if any - for (Stop stop : stops) { - if (stop.updateTime(curTime)) - { - stateChange = true; - stopFractions = null; - stopColors = null; - } - } - - return stateChange; - } -} --- a/src/com/kitfox/svg/Group.java +++ /dev/null @@ -1,340 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on January 26, 2004, 1:56 AM - */ -package com.kitfox.svg; - -import com.kitfox.svg.xml.StyleAttribute; -import java.awt.Graphics2D; -import java.awt.Shape; -import java.awt.geom.AffineTransform; -import java.awt.geom.Area; -import java.awt.geom.NoninvertibleTransformException; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; -import java.util.Iterator; -import java.util.List; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class Group extends ShapeElement -{ - public static final String TAG_NAME = "group"; - - //Cache bounding box for faster clip testing - Rectangle2D boundingBox; - Shape cachedShape; - - /** - * Creates a new instance of Stop - */ - public Group() - { - } - - @Override - public String getTagName() - { - return TAG_NAME; - } - - /** - * Called after the start element but before the end element to indicate - * each child tag that has been processed - */ - @Override - public void loaderAddChild(SVGLoaderHelper helper, SVGElement child) throws SVGElementException - { - super.loaderAddChild(helper, child); - } - - protected boolean outsideClip(Graphics2D g) throws SVGException - { - Shape clip = g.getClip(); - if (clip == null) - { - return false; - } - //g.getClipBounds(clipBounds); - Rectangle2D rect = getBoundingBox(); - - if (clip.intersects(rect)) - { - return false; - } - - return true; - } - - @Override - protected void doPick(Point2D point, boolean boundingBox, List> retVec) throws SVGException - { - Point2D xPoint = new Point2D.Double(point.getX(), point.getY()); - if (xform != null) - { - try - { - xform.inverseTransform(point, xPoint); - } catch (NoninvertibleTransformException ex) - { - throw new SVGException(ex); - } - } - - - for (SVGElement ele : children) { - if (ele instanceof RenderableElement) - { - RenderableElement rendEle = (RenderableElement) ele; - - rendEle.pick(xPoint, boundingBox, retVec); - } - } - } - - @Override - protected void doPick(Rectangle2D pickArea, AffineTransform ltw, boolean boundingBox, List> retVec) throws SVGException - { - if (xform != null) - { - ltw = new AffineTransform(ltw); - ltw.concatenate(xform); - } - - - for (SVGElement ele : children) { - if (ele instanceof RenderableElement) - { - RenderableElement rendEle = (RenderableElement) ele; - - rendEle.pick(pickArea, ltw, boundingBox, retVec); - } - } - } - - @Override - protected void doRender(Graphics2D g) throws SVGException - { - //Don't process if not visible - StyleAttribute styleAttrib = new StyleAttribute(); - //Visibility can be overridden by children - - if (getStyle(styleAttrib.setName("display"))) - { - if (styleAttrib.getStringValue().equals("none")) - { - return; - } - } - - //Do not process offscreen groups - boolean ignoreClip = diagram.ignoringClipHeuristic(); -// if (!ignoreClip && outsideClip(g)) -// { -// return; -// } - - beginLayer(g); - - Iterator it = children.iterator(); - -// try -// { -// g.getClipBounds(clipBounds); -// } -// catch (Exception e) -// { -// //For some reason, getClipBounds can throw a null pointer exception for -// // some types of Graphics2D -// ignoreClip = true; -// } - - Shape clip = g.getClip(); - while (it.hasNext()) - { - SVGElement ele = it.next(); - if (ele instanceof RenderableElement) - { - RenderableElement rendEle = (RenderableElement) ele; - -// if (shapeEle == null) continue; - - if (!(ele instanceof Group)) - { - //Skip if clipping area is outside our bounds - if (!ignoreClip && clip != null - && !clip.intersects(rendEle.getBoundingBox())) - { - continue; - } - } - - rendEle.render(g); - } - } - - finishLayer(g); - } - - /** - * Retrieves the cached bounding box of this group - */ - @Override - public Shape getShape() - { - if (cachedShape == null) - { - calcShape(); - } - return cachedShape; - } - - public void calcShape() - { - Area retShape = new Area(); - - for (SVGElement ele : children) { - if (ele instanceof ShapeElement) - { - ShapeElement shpEle = (ShapeElement) ele; - Shape shape = shpEle.getShape(); - if (shape != null) - { - retShape.add(new Area(shape)); - } - } - } - - cachedShape = shapeToParent(retShape); - } - - /** - * Retrieves the cached bounding box of this group - */ - @Override - public Rectangle2D getBoundingBox() throws SVGException - { - if (boundingBox == null) - { - calcBoundingBox(); - } -// calcBoundingBox(); - return boundingBox; - } - - /** - * Recalculates the bounding box by taking the union of the bounding boxes - * of all children. Caches the result. - * @throws com.kitfox.svg.SVGException - */ - public void calcBoundingBox() throws SVGException - { - Rectangle2D retRect = null; - - for (SVGElement ele : children) { - if (ele instanceof RenderableElement) - { - RenderableElement rendEle = (RenderableElement) ele; - Rectangle2D bounds = rendEle.getBoundingBox(); - if (bounds != null && (bounds.getWidth() != 0 || bounds.getHeight() != 0)) - { - if (retRect == null) - { - retRect = bounds; - } - else - { - if (retRect.getWidth() != 0 || retRect.getHeight() != 0) - { - retRect = retRect.createUnion(bounds); - } - } - } - } - } - -// if (xform != null) -// { -// retRect = xform.createTransformedShape(retRect).getBounds2D(); -// } - - //If no contents, use degenerate rectangle - if (retRect == null) - { - retRect = new Rectangle2D.Float(); - } - - boundingBox = boundsToParent(retRect); - } - - @Override - public boolean updateTime(double curTime) throws SVGException - { - boolean changeState = super.updateTime(curTime); - Iterator it = children.iterator(); - - //Distribute message to all members of this group - while (it.hasNext()) - { - SVGElement ele = it.next(); - boolean updateVal = ele.updateTime(curTime); - - if (updateVal && ele instanceof RenderableElement) - { - ((RenderableElement) ele).setBufferImage(null); - } - - changeState = changeState || updateVal; - - //Update our shape if shape aware children change - if (ele instanceof ShapeElement) - { - cachedShape = null; - } - if (ele instanceof RenderableElement) - { - boundingBox = null; - } - } - - if (changeState) - { - setBufferImage(null); - } - - return changeState; - } -} --- a/src/com/kitfox/svg/Hkern.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on February 20, 2004, 10:00 PM - */ -package com.kitfox.svg; - -import com.kitfox.svg.xml.StyleAttribute; - -/** - * - * @author kitfox - */ -public class Hkern extends SVGElement -{ - - public static final String TAG_NAME = "hkern"; - String u1; - String u2; - int k; - - @Override - public String getTagName() - { - return TAG_NAME; - } - - @Override - protected void build() throws SVGException - { - super.build(); - - StyleAttribute sty = new StyleAttribute(); - - - //Read glyph spacing info - if (getPres(sty.setName("u1"))) - { - u1 = sty.getStringValue(); - } - - if (getPres(sty.setName("u2"))) - { - u2 = sty.getStringValue(); - } - - if (getPres(sty.setName("k"))) - { - k = sty.getIntValue(); - } - } - - @Override - public boolean updateTime(double curTime) throws SVGException - { - //Fonts can't change - return false; - } -} --- a/src/com/kitfox/svg/ImageSVG.java +++ /dev/null @@ -1,398 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on February 20, 2004, 10:00 PM - */ -package com.kitfox.svg; - -import com.kitfox.svg.app.data.Handler; -import com.kitfox.svg.xml.StyleAttribute; -import java.awt.AlphaComposite; -import java.awt.Composite; -import java.awt.Graphics2D; -import java.awt.geom.AffineTransform; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.net.URI; -import java.net.URL; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * Implements an image. - * - * @author Mark McKay - * @author Mark McKay - */ -public class ImageSVG extends RenderableElement -{ - public static final String TAG_NAME = "image"; - - float x = 0f; - float y = 0f; - float width = 0f; - float height = 0f; -// BufferedImage href = null; - URL imageSrc = null; - AffineTransform xform; - Rectangle2D bounds; - - /** - * Creates a new instance of Font - */ - public ImageSVG() - { - } - - @Override - public String getTagName() - { - return TAG_NAME; - } - - @Override - protected void build() throws SVGException - { - super.build(); - - StyleAttribute sty = new StyleAttribute(); - - if (getPres(sty.setName("x"))) - { - x = sty.getFloatValueWithUnits(); - } - - if (getPres(sty.setName("y"))) - { - y = sty.getFloatValueWithUnits(); - } - - if (getPres(sty.setName("width"))) - { - width = sty.getFloatValueWithUnits(); - } - - if (getPres(sty.setName("height"))) - { - height = sty.getFloatValueWithUnits(); - } - - try - { - if (getPres(sty.setName("xlink:href"))) - { - URI src = sty.getURIValue(getXMLBase()); - if ("data".equals(src.getScheme())) - { - imageSrc = new URL(null, src.toASCIIString(), new Handler()); - } - else if (!diagram.getUniverse().isImageDataInlineOnly()) - { - try - { - imageSrc = src.toURL(); - } catch (Exception e) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, - "Could not parse xlink:href " + src, e); - imageSrc = null; - } - } - } - } catch (Exception e) - { - throw new SVGException(e); - } - - if (imageSrc != null) - { - diagram.getUniverse().registerImage(imageSrc); - - //Set widths if not set - BufferedImage img = diagram.getUniverse().getImage(imageSrc); - if (img == null) - { - xform = new AffineTransform(); - bounds = new Rectangle2D.Float(); - return; - } - - if (width == 0) - { - width = img.getWidth(); - } - if (height == 0) - { - height = img.getHeight(); - } - - //Determine image xform - xform = new AffineTransform(); - xform.translate(this.x, this.y); - xform.scale(this.width / img.getWidth(), this.height / img.getHeight()); - } - - bounds = new Rectangle2D.Float(this.x, this.y, this.width, this.height); - } - - public float getX() - { - return x; - } - - public float getY() - { - return y; - } - - public float getWidth() - { - return width; - } - - public float getHeight() - { - return height; - } - - @Override - protected void doPick(Point2D point, boolean boundingBox, List> retVec) throws SVGException - { - if (getBoundingBox().contains(point)) - { - retVec.add(getPath(null)); - } - } - - @Override - protected void doPick(Rectangle2D pickArea, AffineTransform ltw, boolean boundingBox, List> retVec) throws SVGException - { - if (ltw.createTransformedShape(getBoundingBox()).intersects(pickArea)) - { - retVec.add(getPath(null)); - } - } - - @Override - protected void doRender(Graphics2D g) throws SVGException - { - StyleAttribute styleAttrib = new StyleAttribute(); - if (getStyle(styleAttrib.setName("visibility"))) - { - if (!styleAttrib.getStringValue().equals("visible")) - { - return; - } - } - - if (getStyle(styleAttrib.setName("display"))) - { - if (styleAttrib.getStringValue().equals("none")) - { - return; - } - } - - beginLayer(g); - - float opacity = 1f; - if (getStyle(styleAttrib.setName("opacity"))) - { - opacity = styleAttrib.getRatioValue(); - } - - if (opacity <= 0) - { - return; - } - - Composite oldComp = null; - - if (opacity < 1) - { - oldComp = g.getComposite(); - Composite comp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity); - g.setComposite(comp); - } - - BufferedImage img = diagram.getUniverse().getImage(imageSrc); - if (img == null) - { - return; - } - - AffineTransform curXform = g.getTransform(); - g.transform(xform); - - g.drawImage(img, 0, 0, diagram.getCurrentRenderTarget()); - - g.setTransform(curXform); - if (oldComp != null) - { - g.setComposite(oldComp); - } - - finishLayer(g); - } - - @Override - public Rectangle2D getBoundingBox() - { - return boundsToParent(bounds); - } - - /** - * Updates all attributes in this diagram associated with a time event. Ie, - * all attributes with track information. - * - * @return - true if this node has changed state as a result of the time - * update - */ - @Override - public boolean updateTime(double curTime) throws SVGException - { -// if (trackManager.getNumTracks() == 0) return false; - boolean changeState = super.updateTime(curTime); - - //Get current values for parameters - StyleAttribute sty = new StyleAttribute(); - boolean shapeChange = false; - - if (getPres(sty.setName("x"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != x) - { - x = newVal; - shapeChange = true; - } - } - - if (getPres(sty.setName("y"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != y) - { - y = newVal; - shapeChange = true; - } - } - - if (getPres(sty.setName("width"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != width) - { - width = newVal; - shapeChange = true; - } - } - - if (getPres(sty.setName("height"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != height) - { - height = newVal; - shapeChange = true; - } - } - - try - { - if (getPres(sty.setName("xlink:href"))) - { - URI src = sty.getURIValue(getXMLBase()); - - URL newVal = null; - if ("data".equals(src.getScheme())) - { - newVal = new URL(null, src.toASCIIString(), new Handler()); - } else if (!diagram.getUniverse().isImageDataInlineOnly()) - { - newVal = src.toURL(); - } - - if (newVal != null && !newVal.equals(imageSrc)) - { - imageSrc = newVal; - shapeChange = true; - } - } - } catch (IllegalArgumentException ie) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, - "Image provided with illegal value for href: \"" - + sty.getStringValue() + '"', ie); - } catch (Exception e) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, - "Could not parse xlink:href", e); - } - - - if (shapeChange) - { - build(); -// diagram.getUniverse().registerImage(imageSrc); -// -// //Set widths if not set -// BufferedImage img = diagram.getUniverse().getImage(imageSrc); -// if (img == null) -// { -// xform = new AffineTransform(); -// bounds = new Rectangle2D.Float(); -// } -// else -// { -// if (width == 0) width = img.getWidth(); -// if (height == 0) height = img.getHeight(); -// -// //Determine image xform -// xform = new AffineTransform(); -//// xform.setToScale(this.width / img.getWidth(), this.height / img.getHeight()); -//// xform.translate(this.x, this.y); -// xform.translate(this.x, this.y); -// xform.scale(this.width / img.getWidth(), this.height / img.getHeight()); -// -// bounds = new Rectangle2D.Float(this.x, this.y, this.width, this.height); -// } -// -// return true; - } - - return changeState || shapeChange; - } -} --- a/src/com/kitfox/svg/Line.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on January 26, 2004, 5:25 PM - */ -package com.kitfox.svg; - -import com.kitfox.svg.xml.StyleAttribute; -import java.awt.Graphics2D; -import java.awt.Shape; -import java.awt.geom.Line2D; -import java.awt.geom.Rectangle2D; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class Line extends ShapeElement -{ - public static final String TAG_NAME = "line"; - - float x1 = 0f; - float y1 = 0f; - float x2 = 0f; - float y2 = 0f; - Line2D.Float line; - - /** - * Creates a new instance of Rect - */ - public Line() - { - } - - @Override - public String getTagName() - { - return TAG_NAME; - } - - @Override - protected void build() throws SVGException - { - super.build(); - - StyleAttribute sty = new StyleAttribute(); - - if (getPres(sty.setName("x1"))) - { - x1 = sty.getFloatValueWithUnits(); - } - - if (getPres(sty.setName("y1"))) - { - y1 = sty.getFloatValueWithUnits(); - } - - if (getPres(sty.setName("x2"))) - { - x2 = sty.getFloatValueWithUnits(); - } - - if (getPres(sty.setName("y2"))) - { - y2 = sty.getFloatValueWithUnits(); - } - - line = new Line2D.Float(x1, y1, x2, y2); - } - - @Override - protected void doRender(Graphics2D g) throws SVGException - { - beginLayer(g); - renderShape(g, line); - finishLayer(g); - } - - @Override - public Shape getShape() - { - return shapeToParent(line); - } - - @Override - public Rectangle2D getBoundingBox() throws SVGException - { - return boundsToParent(includeStrokeInBounds(line.getBounds2D())); - } - - /** - * Updates all attributes in this diagram associated with a time event. Ie, - * all attributes with track information. - * - * @return - true if this node has changed state as a result of the time - * update - */ - @Override - public boolean updateTime(double curTime) throws SVGException - { -// if (trackManager.getNumTracks() == 0) return false; - boolean changeState = super.updateTime(curTime); - - //Get current values for parameters - StyleAttribute sty = new StyleAttribute(); - boolean shapeChange = false; - - if (getPres(sty.setName("x1"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != x1) - { - x1 = newVal; - shapeChange = true; - } - } - - if (getPres(sty.setName("y1"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != y1) - { - y1 = newVal; - shapeChange = true; - } - } - - if (getPres(sty.setName("x2"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != x2) - { - x2 = newVal; - shapeChange = true; - } - } - - if (getPres(sty.setName("y2"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != y2) - { - y2 = newVal; - shapeChange = true; - } - } - - if (shapeChange) - { - build(); - } - - return changeState || shapeChange; - } -} --- a/src/com/kitfox/svg/LinearGradient.java +++ /dev/null @@ -1,225 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on January 26, 2004, 1:54 AM - */ -package com.kitfox.svg; - -import com.kitfox.svg.xml.StyleAttribute; -import java.awt.Color; -import java.awt.LinearGradientPaint; -import java.awt.MultipleGradientPaint; -import java.awt.Paint; -import java.awt.geom.AffineTransform; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class LinearGradient extends Gradient -{ - public static final String TAG_NAME = "lineargradient"; - - float x1 = 0f; - float y1 = 0f; - float x2 = 1f; - float y2 = 0f; - - /** - * Creates a new instance of LinearGradient - */ - public LinearGradient() - { - } - - @Override - public String getTagName() - { - return TAG_NAME; - } - - @Override - protected void build() throws SVGException - { - super.build(); - - StyleAttribute sty = new StyleAttribute(); - - if (getPres(sty.setName("x1"))) - { - x1 = sty.getFloatValueWithUnits(); - } - - if (getPres(sty.setName("y1"))) - { - y1 = sty.getFloatValueWithUnits(); - } - - if (getPres(sty.setName("x2"))) - { - x2 = sty.getFloatValueWithUnits(); - } - - if (getPres(sty.setName("y2"))) - { - y2 = sty.getFloatValueWithUnits(); - } - } - - @Override - public Paint getPaint(Rectangle2D bounds, AffineTransform xform) - { - MultipleGradientPaint.CycleMethod method; - switch (spreadMethod) - { - default: - case SM_PAD: - method = MultipleGradientPaint.CycleMethod.NO_CYCLE; - break; - case SM_REPEAT: - method = MultipleGradientPaint.CycleMethod.REPEAT; - break; - case SM_REFLECT: - method = MultipleGradientPaint.CycleMethod.REFLECT; - break; - } - - Paint paint; - Point2D.Float pt1 = new Point2D.Float(x1, y1); - Point2D.Float pt2 = new Point2D.Float(x2, y2); - if (pt1.equals(pt2)) - { - Color[] colors = getStopColors(); - paint = colors.length > 0 ? colors[0] : Color.black; - } else if (gradientUnits == GU_USER_SPACE_ON_USE) - { - paint = new LinearGradientPaint( - pt1, - pt2, - getStopFractions(), - getStopColors(), - method, - MultipleGradientPaint.ColorSpaceType.SRGB, - gradientTransform == null - ? new AffineTransform() - : gradientTransform); - } else - { - AffineTransform viewXform = new AffineTransform(); - viewXform.translate(bounds.getX(), bounds.getY()); - - //This is a hack to get around shapes that have a width or height of 0. Should be close enough to the true answer. - double width = Math.max(1, bounds.getWidth()); - double height = Math.max(1, bounds.getHeight()); - viewXform.scale(width, height); - - if (gradientTransform != null) - { - viewXform.concatenate(gradientTransform); - } - - paint = new LinearGradientPaint( - pt1, - pt2, - getStopFractions(), - getStopColors(), - method, - MultipleGradientPaint.ColorSpaceType.SRGB, - viewXform); - } - - return paint; - } - - /** - * Updates all attributes in this diagram associated with a time event. Ie, - * all attributes with track information. - * - * @return - true if this node has changed state as a result of the time - * update - */ - @Override - public boolean updateTime(double curTime) throws SVGException - { -// if (trackManager.getNumTracks() == 0) return stopChange; - boolean changeState = super.updateTime(curTime); - - //Get current values for parameters - StyleAttribute sty = new StyleAttribute(); - boolean shapeChange = false; - - if (getPres(sty.setName("x1"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != x1) - { - x1 = newVal; - shapeChange = true; - } - } - - if (getPres(sty.setName("y1"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != y1) - { - y1 = newVal; - shapeChange = true; - } - } - - if (getPres(sty.setName("x2"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != x2) - { - x2 = newVal; - shapeChange = true; - } - } - - if (getPres(sty.setName("y2"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != y2) - { - y2 = newVal; - shapeChange = true; - } - } - - return changeState || shapeChange; - } -} --- a/src/com/kitfox/svg/Marker.java +++ /dev/null @@ -1,376 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - */ -package com.kitfox.svg; - -import com.kitfox.svg.xml.StyleAttribute; -import java.awt.Graphics2D; -import java.awt.Rectangle; -import java.awt.Shape; -import java.awt.geom.AffineTransform; -import java.awt.geom.PathIterator; -import java.awt.geom.Rectangle2D; -import java.util.ArrayList; - -/** - * - * @author kitfox - */ -public class Marker extends Group -{ - public static final String TAG_NAME = "marker"; - - AffineTransform viewXform; - AffineTransform markerXform; - Rectangle2D viewBox; - float refX; - float refY; - float markerWidth = 1; - float markerHeight = 1; - float orient = Float.NaN; - boolean markerUnitsStrokeWidth = true; //if set to false 'userSpaceOnUse' is assumed - - @Override - public String getTagName() - { - return TAG_NAME; - } - - @Override - protected void build() throws SVGException - { - super.build(); - - StyleAttribute sty = new StyleAttribute(); - - if (getPres(sty.setName("refX"))) - { - refX = sty.getFloatValueWithUnits(); - } - if (getPres(sty.setName("refY"))) - { - refY = sty.getFloatValueWithUnits(); - } - if (getPres(sty.setName("markerWidth"))) - { - markerWidth = sty.getFloatValueWithUnits(); - } - if (getPres(sty.setName("markerHeight"))) - { - markerHeight = sty.getFloatValueWithUnits(); - } - - if (getPres(sty.setName("orient"))) - { - if ("auto".equals(sty.getStringValue())) - { - orient = Float.NaN; - } else - { - orient = sty.getFloatValue(); - } - } - - if (getPres(sty.setName("viewBox"))) - { - float[] dim = sty.getFloatList(); - viewBox = new Rectangle2D.Float(dim[0], dim[1], dim[2], dim[3]); - } - - if (viewBox == null) - { - viewBox = new Rectangle(0, 0, 1, 1); - } - - if (getPres(sty.setName("markerUnits"))) - { - String markerUnits = sty.getStringValue(); - if (markerUnits != null && markerUnits.equals("userSpaceOnUse")) - { - markerUnitsStrokeWidth = false; - } - } - - //Transform pattern onto unit square - viewXform = new AffineTransform(); - viewXform.scale(1.0 / viewBox.getWidth(), 1.0 / viewBox.getHeight()); - viewXform.translate(-viewBox.getX(), -viewBox.getY()); - - markerXform = new AffineTransform(); - markerXform.scale(markerWidth, markerHeight); - markerXform.concatenate(viewXform); - markerXform.translate(-refX, -refY); - } - - @Override - protected boolean outsideClip(Graphics2D g) throws SVGException - { - Shape clip = g.getClip(); - Rectangle2D rect = super.getBoundingBox(); - if (clip == null || clip.intersects(rect)) - { - return false; - } - - return true; - - } - - @Override - protected void doRender(Graphics2D g) throws SVGException - { - AffineTransform oldXform = g.getTransform(); - g.transform(markerXform); - - super.doRender(g); - - g.setTransform(oldXform); - } - - public void render(Graphics2D g, MarkerPos pos, float strokeWidth) throws SVGException - { - AffineTransform cacheXform = g.getTransform(); - - g.translate(pos.x, pos.y); - if (markerUnitsStrokeWidth) - { - g.scale(strokeWidth, strokeWidth); - } - - g.rotate(Math.atan2(pos.dy, pos.dx)); - - g.transform(markerXform); - - super.doRender(g); - - g.setTransform(cacheXform); - } - - @Override - public Shape getShape() - { - Shape shape = super.getShape(); - return markerXform.createTransformedShape(shape); - } - - @Override - public Rectangle2D getBoundingBox() throws SVGException - { - Rectangle2D rect = super.getBoundingBox(); - return markerXform.createTransformedShape(rect).getBounds2D(); - } - - /** - * Updates all attributes in this diagram associated with a time event. Ie, - * all attributes with track information. - * - * @return - true if this node has changed state as a result of the time - * update - */ - @Override - public boolean updateTime(double curTime) throws SVGException - { - boolean changeState = super.updateTime(curTime); - - build(); - - //Marker properties do not change - return changeState; - } - - //-------------------------------- - public static final int MARKER_START = 0; - public static final int MARKER_MID = 1; - public static final int MARKER_END = 2; - - public static class MarkerPos - { - - int type; - double x; - double y; - double dx; - double dy; - - public MarkerPos(int type, double x, double y, double dx, double dy) - { - this.type = type; - this.x = x; - this.y = y; - this.dx = dx; - this.dy = dy; - } - } - - public static class MarkerLayout - { - - private ArrayList markerList = new ArrayList(); - boolean started = false; - - public void layout(Shape shape) - { - double px = 0; - double py = 0; - double[] coords = new double[6]; - for (PathIterator it = shape.getPathIterator(null); - !it.isDone(); it.next()) - { - switch (it.currentSegment(coords)) - { - case PathIterator.SEG_MOVETO: - px = coords[0]; - py = coords[1]; - started = false; - break; - case PathIterator.SEG_CLOSE: - started = false; - break; - case PathIterator.SEG_LINETO: - { - double x = coords[0]; - double y = coords[1]; - markerIn(px, py, x - px, y - py); - markerOut(x, y, x - px, y - py); - px = x; - py = y; - break; - } - case PathIterator.SEG_QUADTO: - { - double k0x = coords[0]; - double k0y = coords[1]; - double x = coords[2]; - double y = coords[3]; - - - //Best in tangent - if (px != k0x || py != k0y) - { - markerIn(px, py, k0x - px, k0y - py); - } else - { - markerIn(px, py, x - px, y - py); - } - - //Best out tangent - if (x != k0x || y != k0y) - { - markerOut(x, y, x - k0x, y - k0y); - } else - { - markerOut(x, y, x - px, y - py); - } - - markerIn(px, py, k0x - px, k0y - py); - markerOut(x, y, x - k0x, y - k0y); - px = x; - py = y; - break; - } - case PathIterator.SEG_CUBICTO: - { - double k0x = coords[0]; - double k0y = coords[1]; - double k1x = coords[2]; - double k1y = coords[3]; - double x = coords[4]; - double y = coords[5]; - - //Best in tangent - if (px != k0x || py != k0y) - { - markerIn(px, py, k0x - px, k0y - py); - } else if (px != k1x || py != k1y) - { - markerIn(px, py, k1x - px, k1y - py); - } else - { - markerIn(px, py, x - px, y - py); - } - - //Best out tangent - if (x != k1x || y != k1y) - { - markerOut(x, y, x - k1x, y - k1y); - } else if (x != k0x || y != k0y) - { - markerOut(x, y, x - k0x, y - k0y); - } else - { - markerOut(x, y, x - px, y - py); - } - px = x; - py = y; - break; - } - } - } - - for (int i = 1; i < markerList.size(); ++i) - { - MarkerPos prev = (MarkerPos) markerList.get(i - 1); - MarkerPos cur = (MarkerPos) markerList.get(i); - - if (cur.type == MARKER_START) - { - prev.type = MARKER_END; - } - } - MarkerPos last = (MarkerPos) markerList.get(markerList.size() - 1); - last.type = MARKER_END; - } - - private void markerIn(double x, double y, double dx, double dy) - { - if (started == false) - { - started = true; - markerList.add(new MarkerPos(MARKER_START, x, y, dx, dy)); - } - } - - private void markerOut(double x, double y, double dx, double dy) - { - markerList.add(new MarkerPos(MARKER_MID, x, y, dx, dy)); - } - - /** - * @return the markerList - */ - public ArrayList getMarkerList() - { - return markerList; - } - } -} --- a/src/com/kitfox/svg/Mask.java +++ /dev/null @@ -1,212 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - */ -package com.kitfox.svg; - -import java.awt.Color; -import java.awt.Composite; -import java.awt.CompositeContext; -import java.awt.Graphics2D; -import java.awt.Rectangle; -import java.awt.RenderingHints; -import java.awt.geom.AffineTransform; -import java.awt.geom.Area; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.awt.image.ColorModel; -import java.awt.image.Raster; -import java.awt.image.WritableRaster; -import java.util.List; - -/** - * Implements the mask element. - * - * @author Jannis Weis - */ -public class Mask extends Group -{ - public static final String TAG_NAME = "mask"; - - @Override - public String getTagName() { - return TAG_NAME; - } - - @Override - public void render(Graphics2D g) - { - } - - public Composite createMaskComposite() - { - return new MaskComposite(); - } - - @Override - void pick(Point2D point, boolean boundingBox, List> retVec) - { - } - - @Override - void pick(Rectangle2D pickArea, AffineTransform ltw, boolean boundingBox, List> retVec) - { - } - - public void pickElement(Point2D point, boolean boundingBox, - List> retVec, RenderableElement element) throws SVGException - { - if (boundingBox) - { - element.doPick(point, true, retVec); - } else - { - Rectangle pickPoint = new Rectangle((int) point.getX(), (int) point.getY(), 1, 1); - BufferedImage img = BufferPainter.paintToBuffer(null, new AffineTransform(), pickPoint, this, Color.BLACK); - // Only try picking the element if the picked point is visible. - if (luminanceToAlpha(img.getRGB(0, 0)) > 0) - { - element.doPick(point, false, retVec); - } - } - } - - public void pickElement(Rectangle2D pickArea, AffineTransform ltw, boolean boundingBox, - List> retVec, RenderableElement element) throws SVGException - { - // If at any point the considered picking area becomes empty we break out early. - if (pickArea.isEmpty()) return; - if (boundingBox) - { - element.doPick(pickArea, ltw,true, retVec); - } else - { - // Clip with the element bounds to avoid creating a larger buffer than needed. - Area transformedBounds = new Area(ltw.createTransformedShape(element.getBoundingBox())); - transformedBounds.intersect(new Area(pickArea)); - if (transformedBounds.isEmpty()) return; - - Rectangle pickRect = transformedBounds.getBounds(); - if (pickRect.isEmpty()) return; - - BufferedImage maskArea = BufferPainter.paintToBuffer(null, ltw, pickRect,this, Color.BLACK); - - // Pick if any pixel in the pick area is visible. - if (hasVisiblePixel(maskArea)) - { - element.doPick(pickArea, ltw, false, retVec); - } - } - } - - private boolean hasVisiblePixel(BufferedImage img) - { - Raster raster = img.getRaster(); - int x = raster.getMinX(); - int w = raster.getWidth(); - int y = raster.getMinY(); - int h = raster.getHeight(); - int[] srcPix = raster.getPixels(x, y, w, h, (int[]) null); - boolean hasVisiblePixel = false; - for (int i = 0; i < srcPix.length; i += 4) - { - int sr = srcPix[i]; - int sg = srcPix[i + 1]; - int sb = srcPix[i + 2]; - if (luminanceToAlpha(sr, sg, sb) > 0) - { - hasVisiblePixel = true; - break; - } - } - return hasVisiblePixel; - } - - private static double luminanceToAlpha(int rgb) - { - return luminanceToAlpha((rgb >> 16) & 0xFF, (rgb >> 8) & 0xFF, rgb & 0xFF); - } - - private static double luminanceToAlpha(int r, int g, int b) - { - // Assuming 'linearRGB' as the 'color-interpolation' value of the mask. - return 0.2125 * r + 0.7154 * g + 0.0721 * b; - } - - private static class MaskComposite implements Composite, CompositeContext - { - - @Override - public CompositeContext createContext(ColorModel srcColorModel, - ColorModel dstColorModel, RenderingHints hints) - { - return this; - } - - @Override - public void dispose() - { - } - - public void composeRGB(int[] src, int[] dst) - { - int w = src.length; - - for (int i = 0; i < w; i += 4) - { - int sr = src[i]; - int sg = src[i + 1]; - int sb = src[i + 2]; - int da = dst[i + 3]; - double luminance = luminanceToAlpha(sr, sg, sb) / 255d; - da *= luminance; - dst[i + 3] = Math.min(255, Math.max(0, da)); - } - } - - @Override - public void compose(Raster src, Raster dstIn, WritableRaster dstOut) { - assert dstIn == dstOut; - assert src.getNumBands() == dstIn.getNumBands(); - - int x = dstOut.getMinX(); - int w = dstOut.getWidth(); - int y = dstOut.getMinY(); - int h = dstOut.getHeight(); - int[] srcPix = src.getPixels(x, y, w, h, (int[]) null); - int[] dstPix = dstIn.getPixels(x, y, w, h, (int[]) null); - composeRGB(srcPix, dstPix); - dstOut.setPixels(x, y, w, h, dstPix); - } - } -} --- a/src/com/kitfox/svg/Metadata.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on September 19, 2004, 1:56 AM - */ -package com.kitfox.svg; - -/** - * Does not hold any information. Included to allow metadata tag to be parsed. - * - * @author Mark McKay - * @author Mark McKay - */ -public class Metadata extends SVGElement -{ - public static final String TAG_NAME = "metadata"; - - /** - * Creates a new instance of Stop - */ - public Metadata() - { - } - - @Override - public String getTagName() - { - return TAG_NAME; - } - - @Override - public boolean updateTime(double curTime) - { - return false; - } -} --- a/src/com/kitfox/svg/MissingGlyph.java +++ /dev/null @@ -1,291 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on February 20, 2004, 10:00 PM - */ -package com.kitfox.svg; - -import com.kitfox.svg.pathcmd.BuildHistory; -import com.kitfox.svg.pathcmd.PathCommand; -import com.kitfox.svg.xml.StyleAttribute; -import java.awt.Graphics2D; -import java.awt.Shape; -import java.awt.geom.AffineTransform; -import java.awt.geom.GeneralPath; -import java.awt.geom.Rectangle2D; -import java.util.Iterator; - -/** - * Implements an embedded font. - * - * SVG specification: http://www.w3.org/TR/SVG/fonts.html - * - * @author Mark McKay - * @author Mark McKay - */ -public class MissingGlyph extends ShapeElement -{ - public static final String TAG_NAME = "missingglyph"; - - //We may define a path - private Shape path = null; - //Alternately, we may have child graphical elements - private float horizAdvX = -1; //Inherits font's value if not set - private float vertOriginX = -1; //Inherits font's value if not set - private float vertOriginY = -1; //Inherits font's value if not set - private float vertAdvY = -1; //Inherits font's value if not set - - /** - * Creates a new instance of Font - */ - public MissingGlyph() - { - } - - @Override - public String getTagName() - { - return TAG_NAME; - } - - /** - * Called after the start element but before the end element to indicate - * each child tag that has been processed - */ - @Override - public void loaderAddChild(SVGLoaderHelper helper, SVGElement child) throws SVGElementException - { - super.loaderAddChild(helper, child); - } - - @Override - protected void build() throws SVGException - { - super.build(); - - StyleAttribute sty = new StyleAttribute(); - - String commandList = ""; - if (getPres(sty.setName("d"))) - { - commandList = sty.getStringValue(); - } - - - //If glyph path was specified, calculate it - if (commandList != null) - { - String fillRule = getStyle(sty.setName("fill-rule")) ? sty.getStringValue() : "nonzero"; - - PathCommand[] commands = parsePathList(commandList); - - GeneralPath buildPath = new GeneralPath( - fillRule.equals("evenodd") ? GeneralPath.WIND_EVEN_ODD : GeneralPath.WIND_NON_ZERO, - commands.length); - - BuildHistory hist = new BuildHistory(); - - for (int i = 0; i < commands.length; i++) - { - PathCommand cmd = commands[i]; - cmd.appendPath(buildPath, hist); - } - - //Reflect glyph path to put it in user coordinate system - AffineTransform at = new AffineTransform(); - at.scale(1, -1); - path = at.createTransformedShape(buildPath); - } - - - //Read glyph spacing info - if (getPres(sty.setName("horiz-adv-x"))) - { - horizAdvX = sty.getFloatValue(); - } - - if (getPres(sty.setName("vert-origin-x"))) - { - vertOriginX = sty.getFloatValue(); - } - - if (getPres(sty.setName("vert-origin-y"))) - { - vertOriginY = sty.getFloatValue(); - } - - if (getPres(sty.setName("vert-adv-y"))) - { - vertAdvY = sty.getFloatValue(); - } - } - - public Shape getPath() - { - return path; - } - - @Override - protected void doRender(Graphics2D g) throws SVGException - { - //Do not push or pop stack - - if (path != null) - { - renderShape(g, path); - } - - Iterator it = children.iterator(); - while (it.hasNext()) - { - SVGElement ele = it.next(); - if (ele instanceof RenderableElement) - { - ((RenderableElement) ele).render(g); - } - } - - //Do not push or pop stack - } - - public float getHorizAdvX() - { - if (horizAdvX == -1) - { - horizAdvX = ((Font) parent).getHorizAdvX(); - } - return horizAdvX; - } - - public float getVertOriginX() - { - if (vertOriginX == -1) - { - vertOriginX = getHorizAdvX() / 2; - } - return vertOriginX; - } - - public float getVertOriginY() - { - if (vertOriginY == -1) - { - vertOriginY = ((Font) parent).getFontFace().getAscent(); - } - return vertOriginY; - } - - public float getVertAdvY() - { - if (vertAdvY == -1) - { - vertAdvY = ((Font) parent).getFontFace().getUnitsPerEm(); - } - return vertAdvY; - - } - - @Override - public Shape getShape() - { - if (path != null) - { - return shapeToParent(path); - } - return null; - } - - @Override - public Rectangle2D getBoundingBox() throws SVGException - { - if (path != null) - { - return boundsToParent(includeStrokeInBounds(path.getBounds2D())); - } - return null; - } - - /** - * Updates all attributes in this diagram associated with a time event. Ie, - * all attributes with track information. - * - * @return - true if this node has changed state as a result of the time - * update - */ - @Override - public boolean updateTime(double curTime) throws SVGException - { - //Fonts can't change - return false; - } - - /** - * @param path the path to set - */ - public void setPath(Shape path) - { - this.path = path; - } - - /** - * @param horizAdvX the horizAdvX to set - */ - public void setHorizAdvX(float horizAdvX) - { - this.horizAdvX = horizAdvX; - } - - /** - * @param vertOriginX the vertOriginX to set - */ - public void setVertOriginX(float vertOriginX) - { - this.vertOriginX = vertOriginX; - } - - /** - * @param vertOriginY the vertOriginY to set - */ - public void setVertOriginY(float vertOriginY) - { - this.vertOriginY = vertOriginY; - } - - /** - * @param vertAdvY the vertAdvY to set - */ - public void setVertAdvY(float vertAdvY) - { - this.vertAdvY = vertAdvY; - } -} --- a/src/com/kitfox/svg/Path.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on January 26, 2004, 5:25 PM - */ -package com.kitfox.svg; - -import com.kitfox.svg.xml.StyleAttribute; -import java.awt.Graphics2D; -import java.awt.Shape; -import java.awt.geom.GeneralPath; -import java.awt.geom.Rectangle2D; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class Path extends ShapeElement -{ - - public static final String TAG_NAME = "path"; -// PathCommand[] commands = null; - int fillRule = GeneralPath.WIND_NON_ZERO; - String d = ""; -// ExtendedGeneralPath path; - GeneralPath path; - - /** - * Creates a new instance of Rect - */ - public Path() - { - } - - @Override - public String getTagName() - { - return TAG_NAME; - } - - @Override - protected void build() throws SVGException - { - super.build(); - - StyleAttribute sty = new StyleAttribute(); - - - String fillRuleStrn = (getStyle(sty.setName("fill-rule"))) ? sty.getStringValue() : "nonzero"; - fillRule = fillRuleStrn.equals("evenodd") ? GeneralPath.WIND_EVEN_ODD : GeneralPath.WIND_NON_ZERO; - - if (getPres(sty.setName("d"))) - { - d = sty.getStringValue(); - } - - path = buildPath(d, fillRule); - } - - @Override - protected void doRender(Graphics2D g) throws SVGException - { - beginLayer(g); - renderShape(g, path); - finishLayer(g); - } - - @Override - public Shape getShape() - { - return shapeToParent(path); - } - - @Override - public Rectangle2D getBoundingBox() throws SVGException - { - return boundsToParent(includeStrokeInBounds(path.getBounds2D())); - } - - /** - * Updates all attributes in this diagram associated with a time event. Ie, - * all attributes with track information. - * - * @return - true if this node has changed state as a result of the time - * update - */ - @Override - public boolean updateTime(double curTime) throws SVGException - { -// if (trackManager.getNumTracks() == 0) return false; - boolean changeState = super.updateTime(curTime); - - //Get current values for parameters - StyleAttribute sty = new StyleAttribute(); - boolean shapeChange = false; - - if (getStyle(sty.setName("fill-rule"))) - { - int newVal = sty.getStringValue().equals("evenodd") - ? GeneralPath.WIND_EVEN_ODD - : GeneralPath.WIND_NON_ZERO; - if (newVal != fillRule) - { - fillRule = newVal; - changeState = true; - } - } - - if (getPres(sty.setName("d"))) - { - String newVal = sty.getStringValue(); - if (!newVal.equals(d)) - { - d = newVal; - shapeChange = true; - } - } - - if (shapeChange) - { - build(); -// path = buildPath(d, fillRule); -// return true; - } - - return changeState || shapeChange; - } -} --- a/src/com/kitfox/svg/PatternSVG.java +++ /dev/null @@ -1,285 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on January 26, 2004, 3:25 AM - */ -package com.kitfox.svg; - -import com.kitfox.svg.pattern.PatternPaint; -import com.kitfox.svg.xml.StyleAttribute; -import java.awt.Graphics2D; -import java.awt.Paint; -import java.awt.RenderingHints; -import java.awt.TexturePaint; -import java.awt.geom.AffineTransform; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.net.URI; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class PatternSVG extends FillElement -{ - public static final String TAG_NAME = "pattern"; - - public static final int GU_OBJECT_BOUNDING_BOX = 0; - public static final int GU_USER_SPACE_ON_USE = 1; - int gradientUnits = GU_OBJECT_BOUNDING_BOX; - float x; - float y; - float width; - float height; - AffineTransform patternXform = new AffineTransform(); - Rectangle2D.Float viewBox; - Paint texPaint; - - /** - * Creates a new instance of Gradient - */ - public PatternSVG() - { - } - - @Override - public String getTagName() - { - return TAG_NAME; - } - - /** - * Called after the start element but before the end element to indicate - * each child tag that has been processed - */ - @Override - public void loaderAddChild(SVGLoaderHelper helper, SVGElement child) throws SVGElementException - { - super.loaderAddChild(helper, child); - } - - @Override - protected void build() throws SVGException - { - super.build(); - - StyleAttribute sty = new StyleAttribute(); - - //Load style string - String href = null; - if (getPres(sty.setName("xlink:href"))) - { - href = sty.getStringValue(); - } - //String href = attrs.getValue("xlink:href"); - //If we have a link to another pattern, initialize ourselves with it's values - if (href != null) - { -//System.err.println("Gradient.loaderStartElement() href '" + href + "'"); - try - { - URI src = getXMLBase().resolve(href); - PatternSVG patSrc = (PatternSVG) diagram.getUniverse().getElement(src); - - gradientUnits = patSrc.gradientUnits; - x = patSrc.x; - y = patSrc.y; - width = patSrc.width; - height = patSrc.height; - viewBox = patSrc.viewBox; - patternXform.setTransform(patSrc.patternXform); - children.addAll(patSrc.children); - } catch (Exception e) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, - "Could not parse xlink:href", e); - } - } - - String gradientUnits = ""; - if (getPres(sty.setName("gradientUnits"))) - { - gradientUnits = sty.getStringValue().toLowerCase(); - } - if (gradientUnits.equals("userspaceonuse")) - { - this.gradientUnits = GU_USER_SPACE_ON_USE; - } else - { - this.gradientUnits = GU_OBJECT_BOUNDING_BOX; - } - - String patternTransform = ""; - if (getPres(sty.setName("patternTransform"))) - { - patternTransform = sty.getStringValue(); - } - patternXform = parseTransform(patternTransform); - - - if (getPres(sty.setName("x"))) - { - x = sty.getFloatValueWithUnits(); - } - - if (getPres(sty.setName("y"))) - { - y = sty.getFloatValueWithUnits(); - } - - if (getPres(sty.setName("width"))) - { - width = sty.getFloatValueWithUnits(); - } - - if (getPres(sty.setName("height"))) - { - height = sty.getFloatValueWithUnits(); - } - - if (getPres(sty.setName("viewBox"))) - { - float[] dim = sty.getFloatList(); - viewBox = new Rectangle2D.Float(dim[0], dim[1], dim[2], dim[3]); - } - - preparePattern(); - } - - /* - public void loaderEndElement(SVGLoaderHelper helper) - { - build(); - } - */ - protected void preparePattern() throws SVGException - { - //For now, treat all fills as UserSpaceOnUse. Otherwise, we'll need - // a different paint for every object. - int tileWidth = (int) width; - int tileHeight = (int) height; - - float stretchX = 1f, stretchY = 1f; - if (!patternXform.isIdentity()) - { - //Scale our source tile so that we can have nice sampling from it. - float xlateX = (float) patternXform.getTranslateX(); - float xlateY = (float) patternXform.getTranslateY(); - - Point2D.Float pt = new Point2D.Float(), pt2 = new Point2D.Float(); - - pt.setLocation(width, 0); - patternXform.transform(pt, pt2); - pt2.x -= xlateX; - pt2.y -= xlateY; - stretchX = (float) Math.sqrt(pt2.x * pt2.x + pt2.y * pt2.y) * 1.5f / width; - - pt.setLocation(height, 0); - patternXform.transform(pt, pt2); - pt2.x -= xlateX; - pt2.y -= xlateY; - stretchY = (float) Math.sqrt(pt2.x * pt2.x + pt2.y * pt2.y) * 1.5f / height; - - tileWidth *= stretchX; - tileHeight *= stretchY; - } - - if (tileWidth == 0 || tileHeight == 0) - { - //Use defaults if tile has degenerate size - return; - } - - BufferedImage buf = new BufferedImage(tileWidth, tileHeight, BufferedImage.TYPE_INT_ARGB); - Graphics2D g = buf.createGraphics(); - g.setClip(0, 0, tileWidth, tileHeight); - g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - - for (SVGElement ele : children) { - if (ele instanceof RenderableElement) - { - AffineTransform xform = new AffineTransform(); - - if (viewBox == null) - { - xform.translate(-x, -y); - } else - { - xform.scale(tileWidth / viewBox.width, tileHeight / viewBox.height); - xform.translate(-viewBox.x, -viewBox.y); - } - - g.setTransform(xform); - ((RenderableElement) ele).render(g); - } - } - - g.dispose(); - -//try { -//javax.imageio.ImageIO.write(buf, "png", new java.io.File("c:\\tmp\\texPaint.png")); -//} catch (Exception e ) {} - - if (patternXform.isIdentity()) - { - texPaint = new TexturePaint(buf, new Rectangle2D.Float(x, y, width, height)); - } else - { - patternXform.scale(1 / stretchX, 1 / stretchY); - texPaint = new PatternPaint(buf, patternXform); - } - } - - @Override - public Paint getPaint(Rectangle2D bounds, AffineTransform xform) - { - return texPaint; - } - - /** - * Updates all attributes in this diagram associated with a time event. Ie, - * all attributes with track information. - * - * @return - true if this node has changed state as a result of the time - * update - */ - @Override - public boolean updateTime(double curTime) throws SVGException - { - //Patterns don't change state - return false; - } -} --- a/src/com/kitfox/svg/Polygon.java +++ /dev/null @@ -1,170 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on January 26, 2004, 5:25 PM - */ -package com.kitfox.svg; - -import com.kitfox.svg.xml.StyleAttribute; -import com.kitfox.svg.xml.XMLParseUtil; -import java.awt.Graphics2D; -import java.awt.Shape; -import java.awt.geom.GeneralPath; -import java.awt.geom.Rectangle2D; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class Polygon extends ShapeElement -{ - public static final String TAG_NAME = "polygon"; - - int fillRule = GeneralPath.WIND_NON_ZERO; - String pointsStrn = ""; - GeneralPath path; - - /** - * Creates a new instance of Rect - */ - public Polygon() - { - } - - @Override - public String getTagName() - { - return TAG_NAME; - } - - @Override - protected void build() throws SVGException - { - super.build(); - - StyleAttribute sty = new StyleAttribute(); - - if (getPres(sty.setName("points"))) - { - pointsStrn = sty.getStringValue(); - } - - String fillRuleStrn = getStyle(sty.setName("fill-rule")) ? sty.getStringValue() : "nonzero"; - fillRule = fillRuleStrn.equals("evenodd") ? GeneralPath.WIND_EVEN_ODD : GeneralPath.WIND_NON_ZERO; - - buildPath(); - } - - protected void buildPath() - { - float[] points = XMLParseUtil.parseFloatList(pointsStrn); - path = new GeneralPath(fillRule, points.length / 2); - - path.moveTo(points[0], points[1]); - for (int i = 2; i < points.length; i += 2) - { - path.lineTo(points[i], points[i + 1]); - } - path.closePath(); - } - - @Override - protected void doRender(Graphics2D g) throws SVGException - { - beginLayer(g); - renderShape(g, path); - finishLayer(g); - } - - @Override - public Shape getShape() - { - return shapeToParent(path); - } - - @Override - public Rectangle2D getBoundingBox() throws SVGException - { - return boundsToParent(includeStrokeInBounds(path.getBounds2D())); - } - - /** - * Updates all attributes in this diagram associated with a time event. Ie, - * all attributes with track information. - * - * @return - true if this node has changed state as a result of the time - * update - */ - @Override - public boolean updateTime(double curTime) throws SVGException - { -// if (trackManager.getNumTracks() == 0) return false; - boolean changeState = super.updateTime(curTime); - - //Get current values for parameters - StyleAttribute sty = new StyleAttribute(); - boolean shapeChange = false; - - if (getStyle(sty.setName("fill-rule"))) - { - int newVal = sty.getStringValue().equals("evenodd") - ? GeneralPath.WIND_EVEN_ODD - : GeneralPath.WIND_NON_ZERO; - if (newVal != fillRule) - { - fillRule = newVal; - shapeChange = true; - } - } - - if (getPres(sty.setName("points"))) - { - String newVal = sty.getStringValue(); - if (!newVal.equals(pointsStrn)) - { - pointsStrn = newVal; - shapeChange = true; - } - } - - - if (shapeChange) - { - build(); -// buildPath(); -// return true; - } - - return changeState || shapeChange; - } -} --- a/src/com/kitfox/svg/Polyline.java +++ /dev/null @@ -1,169 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on January 26, 2004, 5:25 PM - */ -package com.kitfox.svg; - -import com.kitfox.svg.xml.StyleAttribute; -import com.kitfox.svg.xml.XMLParseUtil; -import java.awt.Graphics2D; -import java.awt.Shape; -import java.awt.geom.GeneralPath; -import java.awt.geom.Rectangle2D; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class Polyline extends ShapeElement -{ - public static final String TAG_NAME = "polyline"; - - int fillRule = GeneralPath.WIND_NON_ZERO; - String pointsStrn = ""; - GeneralPath path; - - /** - * Creates a new instance of Rect - */ - public Polyline() - { - } - - @Override - public String getTagName() - { - return TAG_NAME; - } - - @Override - public void build() throws SVGException - { - super.build(); - - StyleAttribute sty = new StyleAttribute(); - - if (getPres(sty.setName("points"))) - { - pointsStrn = sty.getStringValue(); - } - - String fillRuleStrn = getStyle(sty.setName("fill-rule")) ? sty.getStringValue() : "nonzero"; - fillRule = fillRuleStrn.equals("evenodd") ? GeneralPath.WIND_EVEN_ODD : GeneralPath.WIND_NON_ZERO; - - buildPath(); - } - - protected void buildPath() - { - float[] points = XMLParseUtil.parseFloatList(pointsStrn); - path = new GeneralPath(fillRule, points.length / 2); - - path.moveTo(points[0], points[1]); - for (int i = 2; i < points.length; i += 2) - { - path.lineTo(points[i], points[i + 1]); - } - } - - @Override - protected void doRender(Graphics2D g) throws SVGException - { - beginLayer(g); - renderShape(g, path); - finishLayer(g); - } - - @Override - public Shape getShape() - { - return shapeToParent(path); - } - - @Override - public Rectangle2D getBoundingBox() throws SVGException - { - return boundsToParent(includeStrokeInBounds(path.getBounds2D())); - } - - /** - * Updates all attributes in this diagram associated with a time event. Ie, - * all attributes with track information. - * - * @return - true if this node has changed state as a result of the time - * update - */ - @Override - public boolean updateTime(double curTime) throws SVGException - { -// if (trackManager.getNumTracks() == 0) return false; - boolean changeState = super.updateTime(curTime); - - //Get current values for parameters - StyleAttribute sty = new StyleAttribute(); - boolean shapeChange = false; - - if (getStyle(sty.setName("fill-rule"))) - { - int newVal = sty.getStringValue().equals("evenodd") - ? GeneralPath.WIND_EVEN_ODD - : GeneralPath.WIND_NON_ZERO; - if (newVal != fillRule) - { - fillRule = newVal; - shapeChange = true; - } - } - - if (getPres(sty.setName("points"))) - { - String newVal = sty.getStringValue(); - if (!newVal.equals(pointsStrn)) - { - pointsStrn = newVal; - shapeChange = true; - } - } - - - if (shapeChange) - { - build(); -// buildPath(); -// return true; - } - - return changeState || shapeChange; - } -} --- a/src/com/kitfox/svg/RadialGradient.java +++ /dev/null @@ -1,242 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on January 26, 2004, 1:55 AM - */ -package com.kitfox.svg; - -import com.kitfox.svg.xml.StyleAttribute; -import java.awt.Color; -import java.awt.MultipleGradientPaint; -import java.awt.Paint; -import java.awt.RadialGradientPaint; -import java.awt.geom.AffineTransform; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class RadialGradient extends Gradient -{ - public static final String TAG_NAME = "radialgradient"; - - float cx = 0.5f; - float cy = 0.5f; - boolean hasFocus = false; - float fx = 0f; - float fy = 0f; - float r = 0.5f; - - /** - * Creates a new instance of RadialGradient - */ - public RadialGradient() - { - } - - @Override - public String getTagName() - { - return TAG_NAME; - } - - @Override - protected void build() throws SVGException - { - super.build(); - - StyleAttribute sty = new StyleAttribute(); - - if (getPres(sty.setName("cx"))) - { - cx = sty.getFloatValueWithUnits(); - } - - if (getPres(sty.setName("cy"))) - { - cy = sty.getFloatValueWithUnits(); - } - - hasFocus = false; - if (getPres(sty.setName("fx"))) - { - fx = sty.getFloatValueWithUnits(); - hasFocus = true; - } - - if (getPres(sty.setName("fy"))) - { - fy = sty.getFloatValueWithUnits(); - hasFocus = true; - } - - if (getPres(sty.setName("r"))) - { - r = sty.getFloatValueWithUnits(); - } - } - - @Override - public Paint getPaint(Rectangle2D bounds, AffineTransform xform) - { - MultipleGradientPaint.CycleMethod method; - switch (spreadMethod) - { - default: - case SM_PAD: - method = MultipleGradientPaint.CycleMethod.NO_CYCLE; - break; - case SM_REPEAT: - method = MultipleGradientPaint.CycleMethod.REPEAT; - break; - case SM_REFLECT: - method = MultipleGradientPaint.CycleMethod.REFLECT; - break; - } - - Paint paint; - Point2D.Float pt1 = new Point2D.Float(cx, cy); - Point2D.Float pt2 = hasFocus ? new Point2D.Float(fx, fy) : pt1; - float[] stopFractions = getStopFractions(); - Color[] stopColors = getStopColors(); - - //Verify that the stop fractions are valid - { - //for (int i = 0; i < - } - - if (gradientUnits == GU_USER_SPACE_ON_USE) - { - paint = new RadialGradientPaint( - pt1, - r, - pt2, - stopFractions, - stopColors, - method, - MultipleGradientPaint.ColorSpaceType.SRGB, - gradientTransform); - } else - { - AffineTransform viewXform = new AffineTransform(); - viewXform.translate(bounds.getX(), bounds.getY()); - viewXform.scale(bounds.getWidth(), bounds.getHeight()); - - viewXform.concatenate(gradientTransform); - - paint = new RadialGradientPaint( - pt1, - r, - pt2, - stopFractions, - stopColors, - method, - MultipleGradientPaint.ColorSpaceType.SRGB, - viewXform); - } - - return paint; - } - - /** - * Updates all attributes in this diagram associated with a time event. Ie, - * all attributes with track information. - * - * @return - true if this node has changed state as a result of the time - * update - */ - @Override - public boolean updateTime(double curTime) throws SVGException - { -// if (trackManager.getNumTracks() == 0) return false; - boolean changeState = super.updateTime(curTime); - - //Get current values for parameters - StyleAttribute sty = new StyleAttribute(); - boolean shapeChange = false; - - if (getPres(sty.setName("cx"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != cx) - { - cx = newVal; - shapeChange = true; - } - } - - if (getPres(sty.setName("cy"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != cy) - { - cy = newVal; - shapeChange = true; - } - } - - if (getPres(sty.setName("fx"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != fx) - { - fx = newVal; - shapeChange = true; - } - } - - if (getPres(sty.setName("fy"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != fy) - { - fy = newVal; - shapeChange = true; - } - } - - if (getPres(sty.setName("r"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != r) - { - r = newVal; - shapeChange = true; - } - } - - return changeState; - } -} --- a/src/com/kitfox/svg/Rect.java +++ /dev/null @@ -1,317 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on January 26, 2004, 5:25 PM - */ -package com.kitfox.svg; - -import com.kitfox.svg.xml.StyleAttribute; -import java.awt.Graphics2D; -import java.awt.Shape; -import java.awt.geom.Rectangle2D; -import java.awt.geom.RectangularShape; -import java.awt.geom.RoundRectangle2D; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class Rect extends ShapeElement -{ - public static final String TAG_NAME = "rect"; - - float x = 0f; - float y = 0f; - float width = 0f; - float height = 0f; - float rx = 0f; - float ry = 0f; - RectangularShape rect; - - /** - * Creates a new instance of Rect - */ - public Rect() - { - } - - @Override - public String getTagName() - { - return TAG_NAME; - } - - private void writeObject(ObjectOutputStream out) throws IOException - { - out.writeFloat(x); - out.writeFloat(y); - out.writeFloat(width); - out.writeFloat(height); - out.writeFloat(rx); - out.writeFloat(ry); - } - - private void readObject(ObjectInputStream in) throws IOException - { - x = in.readFloat(); - y = in.readFloat(); - width = in.readFloat(); - height = in.readFloat(); - rx = in.readFloat(); - ry = in.readFloat(); - - if (rx == 0f && ry == 0f) - { - rect = new Rectangle2D.Float(x, y, width, height); - } else - { - rect = new RoundRectangle2D.Float(x, y, width, height, rx * 2, ry * 2); - } - } - - /* - public void loaderStartElement(SVGLoaderHelper helper, Attributes attrs, SVGElement parent) - { - //Load style string - super.loaderStartElement(helper, attrs, parent); - - String x = attrs.getValue("x"); - String y = attrs.getValue("y"); - String width = attrs.getValue("width"); - String height = attrs.getValue("height"); - String rx = attrs.getValue("rx"); - String ry = attrs.getValue("ry"); - - if (rx == null) rx = ry; - if (ry == null) ry = rx; - - this.x = XMLParseUtil.parseFloat(x); - this.y = XMLParseUtil.parseFloat(y); - this.width = XMLParseUtil.parseFloat(width); - this.height = XMLParseUtil.parseFloat(height); - if (rx != null) - { - this.rx = XMLParseUtil.parseFloat(rx); - this.ry = XMLParseUtil.parseFloat(ry); - } - - build(); - // setBounds(this.x, this.y, this.width, this.height); - } - */ - @Override - protected void build() throws SVGException - { - super.build(); - - StyleAttribute sty = new StyleAttribute(); - -// SVGElement parent = this.getParent(); -// if (parent instanceof RenderableElement) -// { -// RenderableElement re = (RenderableElement)parent; -// Rectangle2D bounds = re.getBoundingBox(); -// bounds = null; -// } - - - if (getPres(sty.setName("x"))) - { - x = sty.getFloatValueWithUnits(); - } - - if (getPres(sty.setName("y"))) - { - y = sty.getFloatValueWithUnits(); - } - - if (getPres(sty.setName("width"))) - { - width = sty.getFloatValueWithUnits(); - } - - if (getPres(sty.setName("height"))) - { - height = sty.getFloatValueWithUnits(); - } - - boolean rxSet = false; - if (getPres(sty.setName("rx"))) - { - rx = sty.getFloatValueWithUnits(); - rxSet = true; - } - - boolean rySet = false; - if (getPres(sty.setName("ry"))) - { - ry = sty.getFloatValueWithUnits(); - rySet = true; - } - - if (!rxSet) - { - rx = ry; - } - if (!rySet) - { - ry = rx; - } - - - if (rx == 0f && ry == 0f) - { - rect = new Rectangle2D.Float(x, y, width, height); - } else - { - rect = new RoundRectangle2D.Float(x, y, width, height, rx * 2, ry * 2); - } - } - - @Override - protected void doRender(Graphics2D g) throws SVGException - { - beginLayer(g); - renderShape(g, rect); - finishLayer(g); - } - - @Override - public Shape getShape() - { - return shapeToParent(rect); - } - - @Override - public Rectangle2D getBoundingBox() throws SVGException - { - return boundsToParent(includeStrokeInBounds(rect.getBounds2D())); - } - - /** - * Updates all attributes in this diagram associated with a time event. Ie, - * all attributes with track information. - * - * @return - true if this node has changed state as a result of the time - * update - */ - @Override - public boolean updateTime(double curTime) throws SVGException - { -// if (trackManager.getNumTracks() == 0) return false; - boolean changeState = super.updateTime(curTime); - - //Get current values for parameters - StyleAttribute sty = new StyleAttribute(); - boolean shapeChange = false; - - if (getPres(sty.setName("x"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != x) - { - x = newVal; - shapeChange = true; - } - } - - if (getPres(sty.setName("y"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != y) - { - y = newVal; - shapeChange = true; - } - } - - if (getPres(sty.setName("width"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != width) - { - width = newVal; - shapeChange = true; - } - } - - if (getPres(sty.setName("height"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != height) - { - height = newVal; - shapeChange = true; - } - } - - if (getPres(sty.setName("rx"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != rx) - { - rx = newVal; - shapeChange = true; - } - } - - if (getPres(sty.setName("ry"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != ry) - { - ry = newVal; - shapeChange = true; - } - } - - if (shapeChange) - { - build(); -// if (rx == 0f && ry == 0f) -// { -// rect = new Rectangle2D.Float(x, y, width, height); -// } -// else -// { -// rect = new RoundRectangle2D.Float(x, y, width, height, rx * 2, ry * 2); -// } -// return true; - } - - return changeState || shapeChange; - } -} --- a/src/com/kitfox/svg/RenderableElement.java +++ /dev/null @@ -1,255 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on January 26, 2004, 9:00 AM - */ -package com.kitfox.svg; - -import com.kitfox.svg.xml.StyleAttribute; -import java.awt.Graphics2D; -import java.awt.Shape; -import java.awt.geom.AffineTransform; -import java.awt.geom.Area; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; -import java.net.URI; -import java.util.List; - -/** - * Maintains bounding box for this element - * - * @author Mark McKay - * @author Mark McKay - */ -abstract public class RenderableElement extends TransformableElement -{ - AffineTransform cachedXform = null; - - Mask cachedMask; - Filter filter; - Shape cachedClip = null; - public static final int VECTOR_EFFECT_NONE = 0; - public static final int VECTOR_EFFECT_NON_SCALING_STROKE = 1; - int vectorEffect; - - private BufferPainter.Cache bufferCache; - - /** - * Creates a new instance of BoundedElement - */ - public RenderableElement() - { - } - - public RenderableElement(String id, SVGElement parent) - { - super(id, parent); - } - - BufferPainter.Cache getBufferCache() - { - return bufferCache; - } - - void setBufferImage(BufferPainter.Cache bufferCache) - { - this.bufferCache = bufferCache; - } - - @Override - protected void build() throws SVGException - { - super.build(); - - StyleAttribute sty = new StyleAttribute(); - - if (getPres(sty.setName("vector-effect"))) - { - if ("non-scaling-stroke".equals(sty.getStringValue())) - { - vectorEffect = VECTOR_EFFECT_NON_SCALING_STROKE; - } else - { - vectorEffect = VECTOR_EFFECT_NONE; - } - } else - { - vectorEffect = VECTOR_EFFECT_NONE; - } - - cachedMask = getMask(sty); - filter = getFilter(sty); - } - - public void render(Graphics2D g) throws SVGException - { - BufferPainter.paintElement(g, this); - } - - private Mask getMask(StyleAttribute styleAttrib) throws SVGException - { - if (getStyle(styleAttrib.setName("mask"), false) - && !"none".equals(styleAttrib.getStringValue())) { - URI uri = styleAttrib.getURIValue(getXMLBase()); - if (uri == null) { - return null; - } - return (Mask) diagram.getUniverse().getElement(uri); - } - return null; - } - - private Filter getFilter(StyleAttribute styleAttrib) throws SVGException - { - if (getStyle(styleAttrib.setName("filter"), false) - && !"none".equals(styleAttrib.getStringValue())) { - URI uri = styleAttrib.getURIValue(getXMLBase()); - if (uri == null) { - return null; - } - return (Filter) diagram.getUniverse().getElement(uri); - } - return null; - } - - abstract protected void doRender(Graphics2D g) throws SVGException; - - void pick(Point2D point, boolean boundingBox, List> retVec) throws SVGException - { - if (cachedMask != null) - { - cachedMask.pickElement(point, boundingBox, retVec, this); - } else - { - doPick(point, boundingBox, retVec); - } - } - - protected abstract void doPick(Point2D point, boolean boundingBox, List> retVec) throws SVGException; - - void pick(Rectangle2D pickArea, AffineTransform ltw, boolean boundingBox, List> retVec) throws SVGException - { - if (cachedMask != null) - { - cachedMask.pickElement(pickArea, ltw, boundingBox, retVec, this); - } else - { - doPick(pickArea, ltw, boundingBox, retVec); - } - } - - protected abstract void doPick(Rectangle2D pickArea, AffineTransform ltw, boolean boundingBox, List> retVec) throws SVGException; - - abstract public Rectangle2D getBoundingBox() throws SVGException; - /* - public void loaderStartElement(SVGLoaderHelper helper, Attributes attrs, SVGElement parent) - { - super.loaderStartElement(helper, attrs, parent); - } - */ - - /** - * Pushes transform stack, transforms to local coordinates and sets up - * clipping mask. - * - * @param g Graphics context - * @throws com.kitfox.svg.SVGException - */ - protected void beginLayer(Graphics2D g) throws SVGException - { - if (xform != null) - { - cachedXform = g.getTransform(); - g.transform(xform); - } - - StyleAttribute styleAttrib = new StyleAttribute(); - - //Get clipping path -// StyleAttribute styleAttrib = getStyle("clip-path", false); - Shape clipPath = null; - int clipPathUnits = ClipPath.CP_USER_SPACE_ON_USE; - if (getStyle(styleAttrib.setName("clip-path"), false) - && !"none".equals(styleAttrib.getStringValue())) - { - URI uri = styleAttrib.getURIValue(getXMLBase()); - if (uri != null) - { - ClipPath ele = (ClipPath) diagram.getUniverse().getElement(uri); - clipPath = ele.getClipPathShape(); - clipPathUnits = ele.getClipPathUnits(); - } - } - - //Return if we're out of clipping range - if (clipPath != null) - { - if (clipPathUnits == ClipPath.CP_OBJECT_BOUNDING_BOX && (this instanceof ShapeElement)) - { - Rectangle2D rect = ((ShapeElement) this).getBoundingBox(); - AffineTransform at = new AffineTransform(); - at.scale(rect.getWidth(), rect.getHeight()); - clipPath = at.createTransformedShape(clipPath); - } - - cachedClip = g.getClip(); - if (cachedClip == null) - { - g.setClip(clipPath); - } else - { - Area newClip = new Area(cachedClip); - newClip.intersect(new Area(clipPath)); - g.setClip(newClip); - } - } - } - - /** - * Restores transform and clipping values to the way they were before this - * layer was drawn. - * @param g - */ - protected void finishLayer(Graphics2D g) - { - if (cachedClip != null) - { - g.setClip(cachedClip); - } - - if (cachedXform != null) - { - g.setTransform(cachedXform); - } - } -} --- a/src/com/kitfox/svg/SVGCache.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on April 2, 2005, 1:54 AM - */ - -package com.kitfox.svg; - -/** - * A convienience singleton for allowing all classes to access a common SVG universe. - * - * @author kitfox - */ -public class SVGCache -{ - private static final SVGUniverse svgUniverse = new SVGUniverse(); - - /** Creates a new instance of SVGUniverseSingleton */ - private SVGCache() - { - } - - public static SVGUniverse getSVGUniverse() - { - return svgUniverse; - } - -} --- a/src/com/kitfox/svg/SVGConst.java +++ /dev/null @@ -1,14 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package com.kitfox.svg; - -/** - * - * @author kitfox - */ -public interface SVGConst -{ - public static final String SVG_LOGGER = "svgSalamandeLogger"; -} --- a/src/com/kitfox/svg/SVGDiagram.java +++ /dev/null @@ -1,286 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on February 18, 2004, 5:04 PM - */ - -package com.kitfox.svg; - -import javax.swing.JComponent; -import java.awt.Graphics2D; -import java.awt.Rectangle; -import java.awt.geom.AffineTransform; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; -import java.io.Serializable; -import java.net.URI; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; - - -/** - * Top level structure in an SVG tree. - * - * @author Mark McKay - * @author Mark McKay - */ -public class SVGDiagram implements Serializable -{ - public static final long serialVersionUID = 0; - - //Indexes elements within this SVG diagram - final HashMap idMap = new HashMap(); - - SVGRoot root; - final SVGUniverse universe; - private JComponent renderTarget; - - /** - * This is used by the SVGRoot to determine the width of the - */ - private Rectangle deviceViewport = new Rectangle(100, 100); - - /** - * If true, no attempt will be made to discard geometry based on it being - * out of bounds. This trades potentially drawing many out of bounds - * shapes with having to recalculate bounding boxes every animation iteration. - */ - protected boolean ignoreClipHeuristic = false; - - /** - * URL which uniquely identifies this document - */ -// final URI docRoot; - - /** - * URI that uniquely identifies this document. Also used to resolve - * relative urls. Default base for document. - */ - final URI xmlBase; - - /** - * Creates a new instance of SVGDiagram - * @param xmlBase - * @param universe - */ - public SVGDiagram(URI xmlBase, SVGUniverse universe) - { - this.universe = universe; -// this.docRoot = docRoot; - this.xmlBase = xmlBase; - } - - JComponent getCurrentRenderTarget() - { - return renderTarget; - } - - public void render(JComponent c, Graphics2D g) throws SVGException - { - renderTarget = c; - root.renderToViewport(g); - renderTarget = null; - } - - /** - * Draws this diagram to the passed graphics context - * @param g - * @throws com.kitfox.svg.SVGException - */ - public void render(Graphics2D g) throws SVGException - { - render(null, g); - } - - /** - * Searches thorough the scene graph for all RenderableElements that have - * shapes that contain the passed point. - * - * For every shape which contains the pick point, a List containing the - * path to the node is added to the return list. That is, the result of - * SVGElement.getPath() is added for each entry. - * - * @param point - * @param retVec - * @return the passed in list - * @throws com.kitfox.svg.SVGException - */ - public List> pick(Point2D point, List> retVec) throws SVGException - { - return pick(point, false, retVec); - } - - public List> pick(Point2D point, boolean boundingBox, List> retVec) throws SVGException - { - if (retVec == null) - { - retVec = new ArrayList>(); - } - - root.pick(point, boundingBox, retVec); - - return retVec; - } - - public List> pick(Rectangle2D pickArea, List> retVec) throws SVGException - { - return pick(pickArea, false, retVec); - } - - public List> pick(Rectangle2D pickArea, boolean boundingBox, List> retVec) throws SVGException - { - if (retVec == null) - { - retVec = new ArrayList>(); - } - - root.pick(pickArea, new AffineTransform(), boundingBox, retVec); - - return retVec; - } - - public SVGUniverse getUniverse() - { - return universe; - } - - public URI getXMLBase() - { - return xmlBase; - } - -// public URL getDocRoot() -// { -// return docRoot; -// } - - public float getWidth() - { - if (root == null) return 0; - return root.getDeviceWidth(); - } - - public float getHeight() - { - if (root == null) return 0; - return root.getDeviceHeight(); - } - - /** - * Returns the viewing rectangle of this diagram in device coordinates. - * @param rect - * @return - */ - public Rectangle2D getViewRect(Rectangle2D rect) - { - if (root != null) return root.getDeviceRect(rect); - return rect; - } - - public Rectangle2D getViewRect() - { - return getViewRect(new Rectangle2D.Double()); - } - - public SVGElement getElement(String name) - { - return (SVGElement)idMap.get(name); - } - - public void setElement(String name, SVGElement node) - { - idMap.put(name, node); - } - - public void removeElement(String name) - { - idMap.remove(name); - } - - public SVGRoot getRoot() - { - return root; - } - - public void setRoot(SVGRoot root) - { - this.root = root; - root.setDiagram(this); - } - - public boolean ignoringClipHeuristic() { return ignoreClipHeuristic; } - - public void setIgnoringClipHeuristic(boolean ignoreClipHeuristic) { this.ignoreClipHeuristic = ignoreClipHeuristic; } - - /** - * Updates all attributes in this diagram associated with a time event. - * Ie, all attributes with track information. - * @param curTime - * @throws com.kitfox.svg.SVGException - */ - public void updateTime(double curTime) throws SVGException - { - if (root == null) return; - root.updateTime(curTime); - } - - public Rectangle getDeviceViewport() - { - return deviceViewport; - } - - /** - * Sets the dimensions of the device being rendered into. This is used by - * SVGRoot when its x, y, width or height parameters are specified as - * percentages. - * @param deviceViewport - */ - public void setDeviceViewport(Rectangle deviceViewport) - { - this.deviceViewport.setBounds(deviceViewport); - if (root != null) - { - try - { - root.build(); - } catch (SVGException ex) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, - "Could not build document", ex); - } - } - } -} --- a/src/com/kitfox/svg/SVGDisplayPanel.form +++ /dev/null @@ -1,20 +0,0 @@ - - -
- - - - - - - - - - - - - - - - - --- a/src/com/kitfox/svg/SVGDisplayPanel.java +++ /dev/null @@ -1,211 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on February 20, 2004, 12:29 PM - */ - -package com.kitfox.svg; - -import javax.swing.*; -import java.awt.*; -import java.awt.geom.*; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class SVGDisplayPanel extends javax.swing.JPanel implements Scrollable -{ - public static final long serialVersionUID = 1; - - SVGDiagram diagram = null; - float scale = 1f; - Color bgColor = null; - - /** Creates new form SVGDisplayPanel */ - public SVGDisplayPanel() - { - initComponents(); - } - - public SVGDiagram getDiagram() - { - return diagram; - } - - public void setDiagram(SVGDiagram diagram) - { - this.diagram = diagram; - diagram.setDeviceViewport(getBounds()); - - setDimension(); - } - - public void setScale(float scale) - { - this.scale = scale; - setDimension(); - } - - public void setBgColor(Color col) - { - bgColor = col; - } - - private void setDimension() - { - if (diagram == null) - { - setPreferredSize(new Dimension(1, 1)); - revalidate(); - return; - } - - final Rectangle2D.Float rect = new Rectangle2D.Float(); - diagram.getViewRect(rect); - - int w = (int)(rect.width * scale); - int h = (int)(rect.height * scale); - - setPreferredSize(new Dimension(w, h)); - revalidate(); - } - - /** - * Update this image to reflect the passed time - * @param curTime - * @throws com.kitfox.svg.SVGException - */ - public void updateTime(double curTime) throws SVGException - { - if (diagram == null) return; - - diagram.updateTime(curTime); - } - - @Override - public void paintComponent(Graphics gg) - { - Graphics2D g = (Graphics2D)gg; - - if (bgColor != null) - { - Dimension dim = getSize(); - g.setColor(bgColor); - g.fillRect(0, 0, dim.width, dim.height); - } - - g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); - if (diagram != null) - { - try - { - diagram.render(g); - } - catch (SVGException e) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, - "Could not render diagram", e); - } - } - } - - /** This method is called from within the constructor to - * initialize the form. - * WARNING: Do NOT modify this code. The content of this method is - * always regenerated by the Form Editor. - */ - // //GEN-BEGIN:initComponents - private void initComponents() - { - - setLayout(new java.awt.BorderLayout()); - - addComponentListener(new java.awt.event.ComponentAdapter() - { - @Override - public void componentResized(java.awt.event.ComponentEvent evt) - { - formComponentResized(evt); - } - }); - - }// //GEN-END:initComponents - - private void formComponentResized(java.awt.event.ComponentEvent evt)//GEN-FIRST:event_formComponentResized - {//GEN-HEADEREND:event_formComponentResized - if (diagram != null) - { - diagram.setDeviceViewport(getBounds()); - setDimension(); - } - - }//GEN-LAST:event_formComponentResized - - public Dimension getPreferredScrollableViewportSize() - { - return getPreferredSize(); - } - - public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) - { - if (orientation == SwingConstants.HORIZONTAL) - { - return visibleRect.width; - } - else return visibleRect.height; - } - - public boolean getScrollableTracksViewportHeight() - { - return false; - } - - public boolean getScrollableTracksViewportWidth() - { - return false; - } - - public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) - { - return getScrollableBlockIncrement(visibleRect, orientation, direction) / 16; - } - - - // Variables declaration - do not modify//GEN-BEGIN:variables - // End of variables declaration//GEN-END:variables - -} --- a/src/com/kitfox/svg/SVGElement.java +++ /dev/null @@ -1,863 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on January 26, 2004, 1:59 AM - */ -package com.kitfox.svg; - -import com.kitfox.svg.animation.AnimationElement; -import com.kitfox.svg.animation.TrackBase; -import com.kitfox.svg.animation.TrackManager; -import com.kitfox.svg.pathcmd.BuildHistory; -import com.kitfox.svg.pathcmd.PathCommand; -import com.kitfox.svg.pathcmd.PathParser; -import com.kitfox.svg.xml.StyleAttribute; -import com.kitfox.svg.xml.StyleSheet; -import com.kitfox.svg.xml.XMLParseUtil; -import org.xml.sax.Attributes; -import org.xml.sax.SAXException; - -import java.awt.geom.AffineTransform; -import java.awt.geom.GeneralPath; -import java.io.Serializable; -import java.net.URI; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - - -/** - * @author Mark McKay - * @author Mark McKay - */ -abstract public class SVGElement implements Serializable -{ - - public static final long serialVersionUID = 0; - public static final String SVG_NS = "http://www.w3.org/2000/svg"; - protected SVGElement parent = null; - protected final ArrayList children = new ArrayList(); - protected String id = null; - /** - * CSS class. Used for applying style sheet information. - */ - protected String cssClass = null; - /** - * Styles defined for this elemnt via the style attribute. - */ - protected final HashMap inlineStyles = new HashMap(); - /** - * Presentation attributes set for this element. Ie, any attribute other - * than the style attribute. - */ - protected final HashMap presAttribs = new HashMap(); - /** - * This element may override the URI we resolve against with an xml:base - * attribute. If so, a copy is placed here. Otherwise, we defer to our - * parent for the reolution base - */ - protected URI xmlBase = null; - /** - * The diagram this element belongs to - */ - protected SVGDiagram diagram; - /** - * Link to the universe we reside in - */ - protected final TrackManager trackManager = new TrackManager(); - boolean dirty = true; - - /** - * Creates a new instance of SVGElement - */ - public SVGElement() - { - this(null, null, null); - } - - public SVGElement(String id, SVGElement parent) - { - this(id, null, parent); - } - - public SVGElement(String id, String cssClass, SVGElement parent) - { - this.id = id; - this.cssClass = cssClass; - this.parent = parent; - } - - abstract public String getTagName(); - - public SVGElement getParent() - { - return parent; - } - - void setParent(SVGElement parent) - { - this.parent = parent; - } - - /** - * @param retVec - * @return an ordered list of nodes from the root of the tree to this node - */ - public List getPath(List retVec) - { - if (retVec == null) - { - retVec = new ArrayList(); - } - - if (parent != null) - { - parent.getPath(retVec); - } - retVec.add(this); - - return retVec; - } - - /** - * @param retVec - A list to add all children to. If null, a new list is - * created and children of this group are added. - * - * @return The list containing the children of this group - */ - public List getChildren(List retVec) - { - if (retVec == null) - { - retVec = new ArrayList(); - } - - retVec.addAll(children); - - return retVec; - } - - /** - * @param id - Id of svg element to return - * @return the child of the given id, or null if no such child exists. - */ - public SVGElement getChild(String id) - { - for (SVGElement ele : children) { - String eleId = ele.getId(); - if (eleId != null && eleId.equals(id)) - { - return ele; - } - } - - return null; - } - - /** - * Searches children for given element. If found, returns index of child. - * Otherwise returns -1. - * @param child - * @return index of child - */ - public int indexOfChild(SVGElement child) - { - return children.indexOf(child); - } - - /** - * Swaps 2 elements in children. - * - * @param i index of first child - * @param j index of second child - * @throws com.kitfox.svg.SVGException - */ - public void swapChildren(int i, int j) throws SVGException - { - if ((children == null) || (i < 0) || (i >= children.size()) || (j < 0) || (j >= children.size())) - { - return; - } - - SVGElement temp = children.get(i); - children.set(i, children.get(j)); - children.set(j, temp); - build(); - } - - /** - * Called during SAX load process to notify that this tag has begun the - * process of being loaded - * - * @param attrs - Attributes of this tag - * @param helper - An object passed to all SVG elements involved in this - * build process to aid in sharing information. - * @param parent - * @throws org.xml.sax.SAXException - */ - public void loaderStartElement(SVGLoaderHelper helper, Attributes attrs, SVGElement parent) throws SAXException - { - //Set identification info - this.parent = parent; - this.diagram = helper.diagram; - - this.id = attrs.getValue("id"); - if (this.id != null && !this.id.equals("")) - { - this.id = this.id.intern(); - diagram.setElement(this.id, this); - } - - String className = attrs.getValue("class"); - this.cssClass = (className == null || className.equals("")) ? null : className.intern(); - //docRoot = helper.docRoot; - //universe = helper.universe; - - //Parse style string, if any - String style = attrs.getValue("style"); - if (style != null) - { - HashMap map = XMLParseUtil.parseStyle(style, inlineStyles); - } - - String base = attrs.getValue("xml:base"); - if (base != null && !base.equals("")) - { - try - { - xmlBase = new URI(base); - } catch (Exception e) - { - throw new SAXException(e); - } - } - - //Place all other attributes into the presentation attribute list - int numAttrs = attrs.getLength(); - for (int i = 0; i < numAttrs; i++) - { - String name = attrs.getQName(i).intern(); - String value = attrs.getValue(i); - - presAttribs.put(name, new StyleAttribute(name, value == null ? null : value.intern())); - } - } - - public void removeAttribute(String name, int attribType) - { - switch (attribType) - { - case AnimationElement.AT_CSS: - inlineStyles.remove(name); - return; - case AnimationElement.AT_XML: - presAttribs.remove(name); - return; - } - } - - public void addAttribute(String name, int attribType, String value) throws SVGElementException - { - if (hasAttribute(name, attribType)) - { - throw new SVGElementException(this, "Attribute " + name + "(" + AnimationElement.animationElementToString(attribType) + ") already exists"); - } - - //Alter layout for id attribute - if ("id".equals(name)) - { - if (diagram != null) - { - diagram.removeElement(id); - diagram.setElement(value, this); - } - this.id = value; - } - - switch (attribType) - { - case AnimationElement.AT_CSS: - inlineStyles.put(name, new StyleAttribute(name, value)); - return; - case AnimationElement.AT_XML: - presAttribs.put(name, new StyleAttribute(name, value)); - return; - } - - throw new SVGElementException(this, "Invalid attribute type " + attribType); - } - - public boolean hasAttribute(String name, int attribType) throws SVGElementException - { - switch (attribType) - { - case AnimationElement.AT_CSS: - return inlineStyles.containsKey(name); - case AnimationElement.AT_XML: - return presAttribs.containsKey(name); - case AnimationElement.AT_AUTO: - return inlineStyles.containsKey(name) || presAttribs.containsKey(name); - } - - throw new SVGElementException(this, "Invalid attribute type " + attribType); - } - - /** - * @return a set of Strings that correspond to CSS attributes on this element - */ - public Set getInlineAttributes() - { - return inlineStyles.keySet(); - } - - /** - * @return a set of Strings that correspond to XML attributes on this element - */ - public Set getPresentationAttributes() - { - return presAttribs.keySet(); - } - - /** - * Called after the start element but before the end element to indicate - * each child tag that has been processed - * @param helper - * @param child - * @throws com.kitfox.svg.SVGElementException - */ - public void loaderAddChild(SVGLoaderHelper helper, SVGElement child) throws SVGElementException - { - children.add(child); - child.parent = this; - child.setDiagram(diagram); - - //Add info to track if we've scanned animation element - if (child instanceof AnimationElement) - { - trackManager.addTrackElement((AnimationElement) child); - } - } - - protected void setDiagram(SVGDiagram diagram) - { - this.diagram = diagram; - diagram.setElement(id, this); - for (SVGElement ele : children) { - ele.setDiagram(diagram); - } - } - - public void removeChild(SVGElement child) throws SVGElementException - { - if (!children.contains(child)) - { - throw new SVGElementException(this, "Element does not contain child " + child); - } - - children.remove(child); - } - - /** - * Called during load process to add text scanned within a tag - * @param helper - * @param text - */ - public void loaderAddText(SVGLoaderHelper helper, String text) - { - } - - /** - * Called to indicate that this tag and the tags it contains have been - * completely processed, and that it should finish any load processes. - * @param helper - * @throws com.kitfox.svg.SVGParseException - */ - public void loaderEndElement(SVGLoaderHelper helper) throws SVGParseException - { -// try -// { -// build(); -// } -// catch (SVGException se) -// { -// throw new SVGParseException(se); -// } - } - - /** - * Called by internal processes to rebuild the geometry of this node from - * it's presentation attributes, style attributes and animated tracks. - * @throws com.kitfox.svg.SVGException - */ - protected void build() throws SVGException - { - StyleAttribute sty = new StyleAttribute(); - - if (getPres(sty.setName("id"))) - { - String newId = sty.getStringValue(); - if (!newId.equals(id)) - { - diagram.removeElement(id); - id = newId; - diagram.setElement(this.id, this); - } - } - if (getPres(sty.setName("class"))) - { - cssClass = sty.getStringValue(); - } - if (getPres(sty.setName("xml:base"))) - { - xmlBase = sty.getURIValue(); - } - - //Build children - for (int i = 0; i < children.size(); ++i) - { - SVGElement ele = (SVGElement) children.get(i); - ele.build(); - } - } - - public URI getXMLBase() - { - return xmlBase != null ? xmlBase - : (parent != null ? parent.getXMLBase() : diagram.getXMLBase()); - } - - /** - * @return the id assigned to this node. Null if no id explicitly set. - */ - public String getId() - { - return id; - } - LinkedList contexts = new LinkedList(); - - /** - * Hack to allow nodes to temporarily change their parents. The Use tag will - * need this so it can alter the attributes that a particular node uses. - * @param context - */ - protected void pushParentContext(SVGElement context) - { - contexts.addLast(context); - } - - protected SVGElement popParentContext() - { - return (SVGElement) contexts.removeLast(); - } - - protected SVGElement getParentContext() - { - return contexts.isEmpty() ? null : (SVGElement) contexts.getLast(); - } - - public SVGRoot getRoot() - { - return parent == null ? null : parent.getRoot(); - } - - /* - * Returns the named style attribute. Checks for inline styles first, then - * internal and extranal style sheets, and finally checks for presentation - * attributes. - * @param styleName - Name of attribute to return - * @param recursive - If true and this object does not contain the - * named style attribute, checks attributes of parents abck to root until - * one found. - */ - public boolean getStyle(StyleAttribute attrib) throws SVGException - { - return getStyle(attrib, true); - } - - public void setAttribute(String name, int attribType, String value) throws SVGElementException - { - StyleAttribute styAttr; - - - switch (attribType) - { - case AnimationElement.AT_CSS: - { - styAttr = (StyleAttribute) inlineStyles.get(name); - break; - } - case AnimationElement.AT_XML: - { - styAttr = (StyleAttribute) presAttribs.get(name); - break; - } - case AnimationElement.AT_AUTO: - { - styAttr = (StyleAttribute) inlineStyles.get(name); - - if (styAttr == null) - { - styAttr = (StyleAttribute) presAttribs.get(name); - } - break; - } - default: - throw new SVGElementException(this, "Invalid attribute type " + attribType); - } - - if (styAttr == null) - { - throw new SVGElementException(this, "Could not find attribute " + name + "(" + AnimationElement.animationElementToString(attribType) + "). Make sure to create attribute before setting it."); - } - - //Alter layout for relevant attributes - if ("id".equals(styAttr.getName())) - { - if (diagram != null) - { - diagram.removeElement(this.id); - diagram.setElement(value, this); - } - this.id = value; - } - - styAttr.setStringValue(value); - } - - public boolean getStyle(StyleAttribute attrib, boolean recursive) throws SVGException - { - return getStyle(attrib, recursive, true); - } - - /** - * Copies the current style into the passed style attribute. Checks for - * inline styles first, then internal and extranal style sheets, and finally - * checks for presentation attributes. Recursively checks parents. - * - * @param attrib - Attribute to write style data to. Must have it's name set - * to the name of the style being queried. - * @param recursive - If true and this object does not contain the named - * style attribute, checks attributes of parents back to root until one - * found. - * @param evalAnimation - * @return - */ - public boolean getStyle(StyleAttribute attrib, boolean recursive, boolean evalAnimation) - throws SVGException - { - String styName = attrib.getName(); - - //Check for local inline styles - StyleAttribute styAttr = (StyleAttribute)inlineStyles.get(styName); - - attrib.setStringValue(styAttr == null ? "" : styAttr.getStringValue()); - - //Evalutate corresponding track, if one exists - if (evalAnimation) - { - TrackBase track = trackManager.getTrack(styName, AnimationElement.AT_CSS); - if (track != null) - { - track.getValue(attrib, diagram.getUniverse().getCurTime()); - return true; - } - } - - //Return if we've found a non animated style - if (styAttr != null) - { - return true; - } - - - //Check for presentation attribute - StyleAttribute presAttr = (StyleAttribute)presAttribs.get(styName); - - attrib.setStringValue(presAttr == null ? "" : presAttr.getStringValue()); - - //Evalutate corresponding track, if one exists - if (evalAnimation) - { - TrackBase track = trackManager.getTrack(styName, AnimationElement.AT_XML); - if (track != null) - { - track.getValue(attrib, diagram.getUniverse().getCurTime()); - return true; - } - } - - //Return if we've found a presentation attribute instead - if (presAttr != null) - { - return true; - } - - //Check for style sheet - SVGRoot root = getRoot(); - if (root != null) - { - StyleSheet ss = root.getStyleSheet(); - if (ss != null) - { - return ss.getStyle(attrib, getTagName(), cssClass); - } - } - - //If we're recursive, check parents - if (recursive) - { - SVGElement parentContext = getParentContext(); - if (parentContext != null) - { - return parentContext.getStyle(attrib, true); - } - if (parent != null) - { - return parent.getStyle(attrib, true); - } - } - - //Unsuccessful reading style attribute - return false; - } - - /** - * @param styName - * @return the raw style value of this attribute. Does not take the - * presentation value or animation into consideration. Used by animations to - * determine the base to animate from. - */ - public StyleAttribute getStyleAbsolute(String styName) - { - //Check for local inline styles - return (StyleAttribute) inlineStyles.get(styName); - } - - /** - * Copies the presentation attribute into the passed one. - * - * @param attrib - * @return - True if attribute was read successfully - * @throws com.kitfox.svg.SVGException - */ - public boolean getPres(StyleAttribute attrib) throws SVGException - { - String presName = attrib.getName(); - - //Make sure we have a corresponding presentation attribute - StyleAttribute presAttr = (StyleAttribute) presAttribs.get(presName); - - //Copy presentation value directly - attrib.setStringValue(presAttr == null ? "" : presAttr.getStringValue()); - - //Evalutate corresponding track, if one exists - TrackBase track = trackManager.getTrack(presName, AnimationElement.AT_XML); - if (track != null) - { - track.getValue(attrib, diagram.getUniverse().getCurTime()); - return true; - } - - //Return if we found presentation attribute - if (presAttr != null) - { - return true; - } - - return false; - } - - /** - * @param styName - * @return the raw presentation value of this attribute. Ignores any - * modifications applied by style attributes or animation. Used by - * animations to determine the starting point to animate from - */ - public StyleAttribute getPresAbsolute(String styName) - { - //Check for local inline styles - return (StyleAttribute) presAttribs.get(styName); - } - - private static final Pattern TRANSFORM_PATTERN = Pattern.compile("\\w+\\([^)]*\\)"); - static protected AffineTransform parseTransform(String val) throws SVGException - { - final Matcher matchExpression = TRANSFORM_PATTERN.matcher(""); - - AffineTransform retXform = new AffineTransform(); - - matchExpression.reset(val); - while (matchExpression.find()) - { - retXform.concatenate(parseSingleTransform(matchExpression.group())); - } - - return retXform; - } - - private static final Pattern WORD_PATTERN = Pattern.compile("([a-zA-Z]+|-?\\d+(\\.\\d+)?([eE]-?\\d+)?|-?\\.\\d+([eE]-?\\d+)?)"); - static public AffineTransform parseSingleTransform(String val) throws SVGException - { - final Matcher matchWord = WORD_PATTERN.matcher(""); - - AffineTransform retXform = new AffineTransform(); - - matchWord.reset(val); - if (!matchWord.find()) - { - //Return identity transformation if no data present (eg, empty string) - return retXform; - } - - String function = matchWord.group().toLowerCase(); - - LinkedList termList = new LinkedList(); - while (matchWord.find()) - { - termList.add(matchWord.group()); - } - - - double[] terms = new double[termList.size()]; - Iterator it = termList.iterator(); - int count = 0; - while (it.hasNext()) - { - terms[count++] = XMLParseUtil.parseDouble(it.next()); - } - - //Calculate transformation - if (function.equals("matrix")) - { - retXform.setTransform(terms[0], terms[1], terms[2], terms[3], terms[4], terms[5]); - } else if (function.equals("translate")) - { - if (terms.length == 1) - { - retXform.setToTranslation(terms[0], 0); - } else - { - retXform.setToTranslation(terms[0], terms[1]); - } - } else if (function.equals("scale")) - { - if (terms.length > 1) - { - retXform.setToScale(terms[0], terms[1]); - } else - { - retXform.setToScale(terms[0], terms[0]); - } - } else if (function.equals("rotate")) - { - if (terms.length > 2) - { - retXform.setToRotation(Math.toRadians(terms[0]), terms[1], terms[2]); - } else - { - retXform.setToRotation(Math.toRadians(terms[0])); - } - } else if (function.equals("skewx")) - { - retXform.setToShear(Math.toRadians(terms[0]), 0.0); - } else if (function.equals("skewy")) - { - retXform.setToShear(0.0, Math.toRadians(terms[0])); - } else - { - throw new SVGException("Unknown transform type"); - } - - return retXform; - } - - static protected PathCommand[] parsePathList(String list) - { - return new PathParser(list).parsePathCommand(); - } - - static protected GeneralPath buildPath(String text, int windingRule) - { - PathCommand[] commands = parsePathList(text); - - int numKnots = 2; - for (int i = 0; i < commands.length; i++) - { - numKnots += commands[i].getNumKnotsAdded(); - } - - - GeneralPath path = new GeneralPath(windingRule, numKnots); - - BuildHistory hist = new BuildHistory(); - - for (int i = 0; i < commands.length; i++) - { - PathCommand cmd = commands[i]; - cmd.appendPath(path, hist); - } - - return path; - } - - /** - * Updates all attributes in this diagram associated with a time event. Ie, - * all attributes with track information. - * - * @param curTime - * @return - true if this node has changed state as a result of the time - * update - * @throws com.kitfox.svg.SVGException - */ - abstract public boolean updateTime(double curTime) throws SVGException; - - public int getNumChildren() - { - return children.size(); - } - - public SVGElement getChild(int i) - { - return (SVGElement) children.get(i); - } - - public double lerp(double t0, double t1, double alpha) - { - return (1 - alpha) * t0 + alpha * t1; - } -} --- a/src/com/kitfox/svg/SVGElementException.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on May 12, 2005, 11:32 PM - */ - -package com.kitfox.svg; - -/** - * - * @author kitfox - */ -public class SVGElementException extends SVGException -{ - public static final long serialVersionUID = 0; - - private final SVGElement element; - - /** - * Creates a new instance of SVGException without detail message. - * @param element - */ - public SVGElementException(SVGElement element) - { - this(element, null, null); - } - - - /** - * Constructs an instance of SVGException with the specified detail message. - * @param element - * @param msg the detail message. - */ - public SVGElementException(SVGElement element, String msg) - { - this(element, msg, null); - } - - public SVGElementException(SVGElement element, String msg, Throwable cause) - { - super(msg, cause); - this.element = element; - } - - public SVGElementException(SVGElement element, Throwable cause) - { - this(element, null, cause); - } - - public SVGElement getElement() - { - return element; - } -} --- a/src/com/kitfox/svg/SVGException.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on May 12, 2005, 11:32 PM - */ - -package com.kitfox.svg; - -/** - * - * @author kitfox - */ -public class SVGException extends java.lang.Exception -{ - public static final long serialVersionUID = 0; - - /** - * Creates a new instance of SVGException without detail message. - */ - public SVGException() - { - } - - - /** - * Constructs an instance of SVGException with the specified detail message. - * @param msg the detail message. - */ - public SVGException(String msg) - { - super(msg); - } - - public SVGException(String msg, Throwable cause) - { - super(msg, cause); - } - - public SVGException(Throwable cause) - { - super(cause); - } -} --- a/src/com/kitfox/svg/SVGLoader.java +++ /dev/null @@ -1,303 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on February 18, 2004, 5:09 PM - */ - -package com.kitfox.svg; - - -import java.util.*; -import java.net.*; -import org.xml.sax.*; -import org.xml.sax.helpers.DefaultHandler; - -import com.kitfox.svg.animation.*; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class SVGLoader extends DefaultHandler -{ - final HashMap> nodeClasses = new HashMap>(); - //final HashMap attribClasses = new HashMap(); - final LinkedList buildStack = new LinkedList(); - - final HashSet ignoreClasses = new HashSet(); - - final SVGLoaderHelper helper; - - /** - * The diagram that represents the base of this SVG document we're loading. - * Will be augmented to include node indexing info and other useful stuff. - */ - final SVGDiagram diagram; - -// SVGElement loadRoot; - - //Used to keep track of document elements that are not part of the SVG namespace - int skipNonSVGTagDepth = 0; - int indent = 0; - - final boolean verbose; - - /** - * Creates a new instance of SVGLoader - * @param xmlBase - * @param universe - */ - public SVGLoader(URI xmlBase, SVGUniverse universe) - { - this(xmlBase, universe, false); - } - - public SVGLoader(URI xmlBase, SVGUniverse universe, boolean verbose) - { - this.verbose = verbose; - - diagram = new SVGDiagram(xmlBase, universe); - - //Compile a list of important builder classes - nodeClasses.put("a", A.class); - nodeClasses.put("animate", Animate.class); - nodeClasses.put("animatecolor", AnimateColor.class); - nodeClasses.put("animatemotion", AnimateMotion.class); - nodeClasses.put("animatetransform", AnimateTransform.class); - nodeClasses.put("circle", Circle.class); - nodeClasses.put("clippath", ClipPath.class); - nodeClasses.put("defs", Defs.class); - nodeClasses.put("desc", Desc.class); - nodeClasses.put("ellipse", Ellipse.class); - nodeClasses.put("filter", Filter.class); - nodeClasses.put(FeGaussianBlur.TAG_NAME, FeGaussianBlur.class); - nodeClasses.put("font", Font.class); - nodeClasses.put("font-face", FontFace.class); - nodeClasses.put("g", Group.class); - nodeClasses.put("glyph", Glyph.class); - nodeClasses.put("hkern", Hkern.class); - nodeClasses.put("image", ImageSVG.class); - nodeClasses.put("line", Line.class); - nodeClasses.put("lineargradient", LinearGradient.class); - nodeClasses.put("marker", Marker.class); - nodeClasses.put("mask", Mask.class); - nodeClasses.put("metadata", Metadata.class); - nodeClasses.put("missing-glyph", MissingGlyph.class); - nodeClasses.put("path", Path.class); - nodeClasses.put("pattern", PatternSVG.class); - nodeClasses.put("polygon", Polygon.class); - nodeClasses.put("polyline", Polyline.class); - nodeClasses.put("radialgradient", RadialGradient.class); - nodeClasses.put("rect", Rect.class); - nodeClasses.put("set", SetSmil.class); - nodeClasses.put("shape", ShapeElement.class); - nodeClasses.put("stop", Stop.class); - nodeClasses.put("style", Style.class); - nodeClasses.put("svg", SVGRoot.class); - nodeClasses.put("symbol", Symbol.class); - nodeClasses.put("text", Text.class); - nodeClasses.put("title", Title.class); - nodeClasses.put("tspan", Tspan.class); - nodeClasses.put("use", Use.class); - - ignoreClasses.add("midpointstop"); - - //attribClasses.put("clip-path", StyleUrl.class); - //attribClasses.put("color", StyleColor.class); - - helper = new SVGLoaderHelper(xmlBase, universe, diagram); - } - - private String printIndent(int indent, String indentStrn) - { - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < indent; i++) - { - sb.append(indentStrn); - } - return sb.toString(); - } - - @Override - public void startDocument() throws SAXException - { -// System.err.println("Start doc"); - -// buildStack.clear(); - } - - @Override - public void endDocument() throws SAXException - { -// System.err.println("End doc"); - } - - @Override - public void startElement(String namespaceURI, String sName, String qName, Attributes attrs) throws SAXException - { - if (verbose) - { - System.err.println(printIndent(indent, " ") + "Starting parse of tag " + sName+ ": " + namespaceURI); - } - indent++; - - if (skipNonSVGTagDepth != 0 || (!namespaceURI.equals("") && !namespaceURI.equals(SVGElement.SVG_NS))) - { - skipNonSVGTagDepth++; - return; - } - - sName = sName.toLowerCase(); - -//javax.swing.JOptionPane.showMessageDialog(null, sName); - - Object obj = nodeClasses.get(sName); - if (obj == null) - { - if (!ignoreClasses.contains(sName)) - { - if (verbose) - { - System.err.println("SVGLoader: Could not identify tag '" + sName + "'"); - } - } - return; - } - -//Debug info tag depth -//for (int i = 0; i < buildStack.size(); i++) System.err.print(" "); -//System.err.println("+" + sName); - - try { - Class cls = (Class)obj; - SVGElement svgEle = (SVGElement)cls.newInstance(); - - SVGElement parent = null; - if (buildStack.size() != 0) parent = (SVGElement)buildStack.getLast(); - svgEle.loaderStartElement(helper, attrs, parent); - - buildStack.addLast(svgEle); - } - catch (Exception e) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, - "Could not load", e); - throw new SAXException(e); - } - - } - - @Override - public void endElement(String namespaceURI, String sName, String qName) - throws SAXException - { - indent--; - if (verbose) - { - System.err.println(printIndent(indent, " ") + "Ending parse of tag " + sName+ ": " + namespaceURI); - } - - if (skipNonSVGTagDepth != 0) - { - skipNonSVGTagDepth--; - return; - } - - sName = sName.toLowerCase(); - - Object obj = nodeClasses.get(sName); - if (obj == null) return; - -//Debug info tag depth -//for (int i = 0; i < buildStack.size(); i++) System.err.print(" "); -//System.err.println("-" + sName); - - try { - SVGElement svgEle = (SVGElement)buildStack.removeLast(); - - svgEle.loaderEndElement(helper); - - SVGElement parent = null; - if (buildStack.size() != 0) - { - parent = (SVGElement)buildStack.getLast(); - } - //else loadRoot = (SVGElement)svgEle; - - if (parent != null) - { - parent.loaderAddChild(helper, svgEle); - } - else - { - diagram.setRoot((SVGRoot)svgEle); - } - - } - catch (Exception e) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, - "Could not parse", e); - throw new SAXException(e); - } - } - - @Override - public void characters(char buf[], int offset, int len) - throws SAXException - { - if (skipNonSVGTagDepth != 0) - { - return; - } - - if (buildStack.size() != 0) - { - SVGElement parent = (SVGElement)buildStack.getLast(); - String s = new String(buf, offset, len); - parent.loaderAddText(helper, s); - } - } - - @Override - public void processingInstruction(String target, String data) - throws SAXException - { - //Check for external style sheet - } - -// public SVGElement getLoadRoot() { return loadRoot; } - public SVGDiagram getLoadedDiagram() { return diagram; } -} --- a/src/com/kitfox/svg/SVGLoaderHelper.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on February 18, 2004, 5:37 PM - */ - -package com.kitfox.svg; - -import java.net.*; -import java.io.*; - -import com.kitfox.svg.animation.parser.*; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class SVGLoaderHelper -{ - /** This is the URL that this document is being loaded from */ -// public final URL docRoot; -// public final URI docRoot; - - /** This is the universe of all currently loaded SVG documents */ - public final SVGUniverse universe; - - /** This is the diagram which the load process is currently loading */ - public final SVGDiagram diagram; - - public final URI xmlBase; - - /** - * Animate nodes use this to parse their time strings - */ - public final AnimTimeParser animTimeParser = new AnimTimeParser(new StringReader("")); - - /** - * Creates a new instance of SVGLoaderHelper - * @param xmlBase - * @param universe - * @param diagram - */ - public SVGLoaderHelper(URI xmlBase, SVGUniverse universe, SVGDiagram diagram) - { - this.xmlBase = xmlBase; - this.universe = universe; - this.diagram = diagram; - } - -} --- a/src/com/kitfox/svg/SVGParseException.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on May 12, 2005, 11:32 PM - */ - -package com.kitfox.svg; - -/** - * - * @author kitfox - */ -public class SVGParseException extends java.lang.Exception -{ - public static final long serialVersionUID = 0; - - /** - * Creates a new instance of SVGException without detail message. - */ - public SVGParseException() - { - } - - - /** - * Constructs an instance of SVGException with the specified detail message. - * @param msg the detail message. - */ - public SVGParseException(String msg) - { - super(msg); - } - - public SVGParseException(String msg, Throwable cause) - { - super(msg, cause); - } - - public SVGParseException(Throwable cause) - { - super(cause); - } -} --- a/src/com/kitfox/svg/SVGRoot.java +++ /dev/null @@ -1,496 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on February 18, 2004, 5:33 PM - */ - -package com.kitfox.svg; - -import com.kitfox.svg.xml.NumberWithUnits; -import com.kitfox.svg.xml.StyleAttribute; -import com.kitfox.svg.xml.StyleSheet; -import java.awt.Graphics2D; -import java.awt.Rectangle; -import java.awt.Shape; -import java.awt.geom.AffineTransform; -import java.awt.geom.NoninvertibleTransformException; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; -import java.util.List; - -/** - * The root element of an SVG tree. - * - * @author Mark McKay - * @author Mark McKay - */ -public class SVGRoot extends Group -{ - public static final String TAG_NAME = "svg"; - - NumberWithUnits x; - NumberWithUnits y; - NumberWithUnits width; - NumberWithUnits height; - - Rectangle2D.Float viewBox = null; - - public static final int PA_X_NONE = 0; - public static final int PA_X_MIN = 1; - public static final int PA_X_MID = 2; - public static final int PA_X_MAX = 3; - - public static final int PA_Y_NONE = 0; - public static final int PA_Y_MIN = 1; - public static final int PA_Y_MID = 2; - public static final int PA_Y_MAX = 3; - - public static final int PS_MEET = 0; - public static final int PS_SLICE = 1; - - int parSpecifier = PS_MEET; - int parAlignX = PA_X_MID; - int parAlignY = PA_Y_MID; - - final AffineTransform viewXform = new AffineTransform(); - final Rectangle2D.Float clipRect = new Rectangle2D.Float(); - - private StyleSheet styleSheet; - - /** Creates a new instance of SVGRoot */ - public SVGRoot() - { - } - - @Override - public String getTagName() - { - return TAG_NAME; - } - - @Override - public void build() throws SVGException - { - super.build(); - - StyleAttribute sty = new StyleAttribute(); - - if (getPres(sty.setName("x"))) - { - x = sty.getNumberWithUnits(); - } - - if (getPres(sty.setName("y"))) - { - y = sty.getNumberWithUnits(); - } - - if (getPres(sty.setName("width"))) - { - width = sty.getNumberWithUnits(); - } - - if (getPres(sty.setName("height"))) - { - height = sty.getNumberWithUnits(); - } - - if (getPres(sty.setName("viewBox"))) - { - float[] coords = sty.getFloatList(); - viewBox = new Rectangle2D.Float(coords[0], coords[1], coords[2], coords[3]); - } - - if (getPres(sty.setName("preserveAspectRatio"))) - { - String preserve = sty.getStringValue(); - - if (contains(preserve, "none")) { parAlignX = PA_X_NONE; parAlignY = PA_Y_NONE; } - else if (contains(preserve, "xMinYMin")) { parAlignX = PA_X_MIN; parAlignY = PA_Y_MIN; } - else if (contains(preserve, "xMidYMin")) { parAlignX = PA_X_MID; parAlignY = PA_Y_MIN; } - else if (contains(preserve, "xMaxYMin")) { parAlignX = PA_X_MAX; parAlignY = PA_Y_MIN; } - else if (contains(preserve, "xMinYMid")) { parAlignX = PA_X_MIN; parAlignY = PA_Y_MID; } - else if (contains(preserve, "xMidYMid")) { parAlignX = PA_X_MID; parAlignY = PA_Y_MID; } - else if (contains(preserve, "xMaxYMid")) { parAlignX = PA_X_MAX; parAlignY = PA_Y_MID; } - else if (contains(preserve, "xMinYMax")) { parAlignX = PA_X_MIN; parAlignY = PA_Y_MAX; } - else if (contains(preserve, "xMidYMax")) { parAlignX = PA_X_MID; parAlignY = PA_Y_MAX; } - else if (contains(preserve, "xMaxYMax")) { parAlignX = PA_X_MAX; parAlignY = PA_Y_MAX; } - - if (contains(preserve, "meet")) - { - parSpecifier = PS_MEET; - } - else if (contains(preserve, "slice")) - { - parSpecifier = PS_SLICE; - } - } - - prepareViewport(); - } - - private boolean contains(String text, String find) - { - return (text.indexOf(find) != -1); - } - - @Override - public SVGRoot getRoot() - { - return this; - } - - protected void prepareViewport() - { - Rectangle deviceViewport = diagram.getDeviceViewport(); - - Rectangle2D defaultBounds; - try - { - defaultBounds = getBoundingBox(); - } - catch (SVGException ex) - { - defaultBounds= new Rectangle2D.Float(); - } - - //Determine destination rectangle - float xx, yy, ww, hh; - if (width != null) - { - xx = (x == null) ? 0 : StyleAttribute.convertUnitsToPixels(x.getUnits(), x.getValue()); - if (width.getUnits() == NumberWithUnits.UT_PERCENT) - { - ww = width.getValue() * deviceViewport.width; - } - else - { - ww = StyleAttribute.convertUnitsToPixels(width.getUnits(), width.getValue()); - } - } - else if (viewBox != null) - { - xx = viewBox.x; - ww = viewBox.width; - width = new NumberWithUnits(ww, NumberWithUnits.UT_PX); - x = new NumberWithUnits(xx, NumberWithUnits.UT_PX); - } - else - { - //Estimate size from scene bounding box - xx = (float)defaultBounds.getX(); - ww = (float)defaultBounds.getWidth(); - width = new NumberWithUnits(ww, NumberWithUnits.UT_PX); - x = new NumberWithUnits(xx, NumberWithUnits.UT_PX); - } - - if (height != null) - { - yy = (y == null) ? 0 : StyleAttribute.convertUnitsToPixels(y.getUnits(), y.getValue()); - if (height.getUnits() == NumberWithUnits.UT_PERCENT) - { - hh = height.getValue() * deviceViewport.height; - } - else - { - hh = StyleAttribute.convertUnitsToPixels(height.getUnits(), height.getValue()); - } - } - else if (viewBox != null) - { - yy = viewBox.y; - hh = viewBox.height; - height = new NumberWithUnits(hh, NumberWithUnits.UT_PX); - y = new NumberWithUnits(yy, NumberWithUnits.UT_PX); - } - else - { - //Estimate size from scene bounding box - yy = (float)defaultBounds.getY(); - hh = (float)defaultBounds.getHeight(); - height = new NumberWithUnits(hh, NumberWithUnits.UT_PX); - y = new NumberWithUnits(yy, NumberWithUnits.UT_PX); - } - - clipRect.setRect(xx, yy, ww, hh); - } - - public void renderToViewport(Graphics2D g) throws SVGException - { - render(g); - } - - @Override - protected void doRender(Graphics2D g) throws SVGException - { - prepareViewport(); - - Rectangle targetViewport = g.getClipBounds(); -// -// if (targetViewport == null) -// { -// Dimension size = Toolkit.getDefaultToolkit().getScreenSize(); -// targetViewport = new Rectangle(0, 0, size.width, size.height); -// } -// clipRect.setRect(targetViewport); - - - Rectangle deviceViewport = diagram.getDeviceViewport(); - if (width != null && height != null) - { - float xx, yy, ww, hh; - - xx = (x == null) ? 0 : StyleAttribute.convertUnitsToPixels(x.getUnits(), x.getValue()); - if (width.getUnits() == NumberWithUnits.UT_PERCENT) - { - ww = width.getValue() * deviceViewport.width; - } - else - { - ww = StyleAttribute.convertUnitsToPixels(width.getUnits(), width.getValue()); - } - - yy = (y == null) ? 0 : StyleAttribute.convertUnitsToPixels(y.getUnits(), y.getValue()); - if (height.getUnits() == NumberWithUnits.UT_PERCENT) - { - hh = height.getValue() * deviceViewport.height; - } - else - { - hh = StyleAttribute.convertUnitsToPixels(height.getUnits(), height.getValue()); - } - - targetViewport = new Rectangle((int)xx, (int)yy, (int)ww, (int)hh); - } - else - { - targetViewport = new Rectangle(deviceViewport); - } - clipRect.setRect(targetViewport); - - viewXform.setTransform(calcViewportTransform(targetViewport)); - - AffineTransform cachedXform = g.getTransform(); - g.transform(viewXform); - - super.doRender(g); - - g.setTransform(cachedXform); - } - - public AffineTransform calcViewportTransform(Rectangle targetViewport) - { - AffineTransform xform = new AffineTransform(); - - if (viewBox == null) - { - xform.setToIdentity(); - } - else - { - xform.setToIdentity(); - xform.setToTranslation(targetViewport.x, targetViewport.y); - xform.scale(targetViewport.width, targetViewport.height); - xform.scale(1 / viewBox.width, 1 / viewBox.height); - xform.translate(-viewBox.x, -viewBox.y); - } - - return xform; - } - - @Override - public void doPick(Rectangle2D pickArea, AffineTransform ltw, boolean boundingBox, List> retVec) throws SVGException - { - if (viewXform != null) - { - ltw = new AffineTransform(ltw); - ltw.concatenate(viewXform); - } - - super.doPick(pickArea, ltw, boundingBox, retVec); - } - - @Override - public void doPick(Point2D point, boolean boundingBox, List> retVec) throws SVGException - { - Point2D xPoint = new Point2D.Double(point.getX(), point.getY()); - if (viewXform != null) - { - try - { - viewXform.inverseTransform(point, xPoint); - } catch (NoninvertibleTransformException ex) - { - throw new SVGException(ex); - } - } - - super.doPick(xPoint, boundingBox, retVec); - } - - @Override - public Shape getShape() - { - Shape shape = super.getShape(); - return viewXform.createTransformedShape(shape); - } - - @Override - public Rectangle2D getBoundingBox() throws SVGException - { - Rectangle2D bbox = super.getBoundingBox(); - return viewXform.createTransformedShape(bbox).getBounds2D(); - } - - public float getDeviceWidth() - { - return clipRect.width; - } - - public float getDeviceHeight() - { - return clipRect.height; - } - - public Rectangle2D getDeviceRect(Rectangle2D rect) - { - rect.setRect(clipRect); - return rect; - } - - /** - * Updates all attributes in this diagram associated with a time event. - * Ie, all attributes with track information. - * @return - true if this node has changed state as a result of the time - * update - */ - @Override - public boolean updateTime(double curTime) throws SVGException - { - boolean changeState = super.updateTime(curTime); - - StyleAttribute sty = new StyleAttribute(); - boolean shapeChange = false; - - if (getPres(sty.setName("x"))) - { - NumberWithUnits newVal = sty.getNumberWithUnits(); - if (!newVal.equals(x)) - { - x = newVal; - shapeChange = true; - } - } - - if (getPres(sty.setName("y"))) - { - NumberWithUnits newVal = sty.getNumberWithUnits(); - if (!newVal.equals(y)) - { - y = newVal; - shapeChange = true; - } - } - - if (getPres(sty.setName("width"))) - { - NumberWithUnits newVal = sty.getNumberWithUnits(); - if (!newVal.equals(width)) - { - width = newVal; - shapeChange = true; - } - } - - if (getPres(sty.setName("height"))) - { - NumberWithUnits newVal = sty.getNumberWithUnits(); - if (!newVal.equals(height)) - { - height = newVal; - shapeChange = true; - } - } - - if (getPres(sty.setName("viewBox"))) - { - float[] coords = sty.getFloatList(); - Rectangle2D.Float newViewBox = new Rectangle2D.Float(coords[0], coords[1], coords[2], coords[3]); - if (!newViewBox.equals(viewBox)) - { - viewBox = newViewBox; - shapeChange = true; - } - } - - if (shapeChange) - { - build(); - } - - return changeState || shapeChange; - } - - /** - * @return the styleSheet - */ - public StyleSheet getStyleSheet() - { - if (styleSheet == null) - { - for (int i = 0; i < getNumChildren(); ++i) - { - SVGElement ele = getChild(i); - if (ele instanceof Style) - { - return ((Style)ele).getStyleSheet(); - } - else if (ele instanceof Defs) - { - return ((Defs)ele).getStyleSheet(); - } - } - } - - return styleSheet; - } - - /** - * @param styleSheet the styleSheet to set - */ - public void setStyleSheet(StyleSheet styleSheet) - { - this.styleSheet = styleSheet; - } - -} --- a/src/com/kitfox/svg/SVGUniverse.java +++ /dev/null @@ -1,733 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on February 18, 2004, 11:43 PM - */ -package com.kitfox.svg; - -import com.kitfox.svg.app.beans.SVGIcon; -import com.kitfox.svg.util.Base64InputStream; -import java.awt.Graphics2D; -import java.awt.image.BufferedImage; -import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeSupport; -import java.io.BufferedInputStream; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Reader; -import java.io.Serializable; -import java.lang.ref.SoftReference; -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.zip.GZIPInputStream; -import javax.imageio.ImageIO; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParser; -import javax.xml.parsers.SAXParserFactory; -import org.xml.sax.EntityResolver; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; -import org.xml.sax.SAXParseException; -import org.xml.sax.XMLReader; - -/** - * Many SVG files can be loaded at one time. These files will quite likely need - * to reference one another. The SVG universe provides a container for all these - * files and the means for them to relate to each other. - * - * @author Mark McKay - * @author Mark McKay - */ -public class SVGUniverse implements Serializable -{ - - public static final long serialVersionUID = 0; - transient private PropertyChangeSupport changes = new PropertyChangeSupport(this); - /** - * Maps document URIs to their loaded SVG diagrams. Note that URIs for - * documents loaded from URLs will reflect their URLs and URIs for documents - * initiated from streams will have the scheme svgSalamander. - */ - final HashMap loadedDocs = new HashMap(); - final HashMap loadedFonts = new HashMap(); - final HashMap> loadedImages = new HashMap>(); - public static final String INPUTSTREAM_SCHEME = "svgSalamander"; - /** - * Current time in this universe. Used for resolving attributes that are - * influenced by track information. Time is in milliseconds. Time 0 - * corresponds to the time of 0 in each member diagram. - */ - protected double curTime = 0.0; - private boolean verbose = false; - - //If true, elements will only load image data that is included using inline data: uris - private boolean imageDataInlineOnly = false; - - /** - * Creates a new instance of SVGUniverse - */ - public SVGUniverse() - { - } - - public void addPropertyChangeListener(PropertyChangeListener l) - { - changes.addPropertyChangeListener(l); - } - - public void removePropertyChangeListener(PropertyChangeListener l) - { - changes.removePropertyChangeListener(l); - } - - /** - * Release all loaded SVG document from memory - */ - public void clear() - { - loadedDocs.clear(); - loadedFonts.clear(); - loadedImages.clear(); - } - - /** - * Returns the current animation time in milliseconds. - */ - public double getCurTime() - { - return curTime; - } - - public void setCurTime(double curTime) - { - double oldTime = this.curTime; - this.curTime = curTime; - changes.firePropertyChange("curTime", new Double(oldTime), new Double(curTime)); - } - - /** - * Updates all time influenced style and presentation attributes in all SVG - * documents in this universe. - */ - public void updateTime() throws SVGException - { - for (SVGDiagram dia : loadedDocs.values()) { - dia.updateTime(curTime); - } - } - - /** - * Called by the Font element to let the universe know that a font has been - * loaded and is available. - */ - void registerFont(Font font) - { - loadedFonts.put(font.getFontFace().getFontFamily(), font); - } - - public Font getDefaultFont() - { - for (Font font : loadedFonts.values()) { - return font; - } - return null; - } - - public Font getFont(String fontName) - { - return (Font) loadedFonts.get(fontName); - } - - URL registerImage(URI imageURI) - { - String scheme = imageURI.getScheme(); - if (scheme.equals("data")) - { - String path = imageURI.getRawSchemeSpecificPart(); - int idx = path.indexOf(';'); - String mime = path.substring(0, idx); - String content = path.substring(idx + 1); - - if (content.startsWith("base64")) - { - content = content.substring(6); - try - { -// byte[] buf = new sun.misc.BASE64Decoder().decodeBuffer(content); -// ByteArrayInputStream bais = new ByteArrayInputStream(buf); - ByteArrayInputStream bis = new ByteArrayInputStream(content.getBytes()); - Base64InputStream bais = new Base64InputStream(bis); - - BufferedImage img = ImageIO.read(bais); - - URL url; - int urlIdx = 0; - while (true) - { - url = new URL("inlineImage", "localhost", "img" + urlIdx); - if (!loadedImages.containsKey(url)) - { - break; - } - urlIdx++; - } - - SoftReference ref = new SoftReference(img); - loadedImages.put(url, ref); - - return url; - } catch (IOException ex) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, - "Could not decode inline image", ex); - } - } - return null; - } else - { - try - { - URL url = imageURI.toURL(); - registerImage(url); - return url; - } catch (MalformedURLException ex) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, - "Bad url", ex); - } - return null; - } - } - - void registerImage(URL imageURL) - { - if (loadedImages.containsKey(imageURL)) - { - return; - } - - SoftReference ref; - try - { - String fileName = imageURL.getFile(); - if (".svg".equals(fileName.substring(fileName.length() - 4).toLowerCase())) - { - SVGIcon icon = new SVGIcon(); - icon.setSvgURI(imageURL.toURI()); - - BufferedImage img = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB); - Graphics2D g = img.createGraphics(); - icon.paintIcon(null, g, 0, 0); - g.dispose(); - ref = new SoftReference(img); - } else - { - BufferedImage img = ImageIO.read(imageURL); - ref = new SoftReference(img); - } - loadedImages.put(imageURL, ref); - } catch (Exception e) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, - "Could not load image: " + imageURL, e); - } - } - - BufferedImage getImage(URL imageURL) - { - SoftReference ref = (SoftReference) loadedImages.get(imageURL); - if (ref == null) - { - return null; - } - - BufferedImage img = (BufferedImage) ref.get(); - //If image was cleared from memory, reload it - if (img == null) - { - try - { - img = ImageIO.read(imageURL); - } catch (Exception e) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, - "Could not load image", e); - } - ref = new SoftReference(img); - loadedImages.put(imageURL, ref); - } - - return img; - } - - /** - * Returns the element of the document at the given URI. If the document is - * not already loaded, it will be. - */ - public SVGElement getElement(URI path) - { - return getElement(path, true); - } - - public SVGElement getElement(URL path) - { - try - { - URI uri = new URI(path.toString()); - return getElement(uri, true); - } catch (Exception e) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, - "Could not parse url " + path, e); - } - return null; - } - - public URI cleanUri(URI uri) - { - String scheme = uri.getScheme(); - String schemeSpecific = uri.getSchemeSpecificPart(); - String frag = uri.getFragment(); - - if (schemeSpecific.startsWith("file:///")) - { - //Work around for URIs of resources obtained by Class.getResource() - schemeSpecific = "file:/" + schemeSpecific.substring(8); - } - else - { - return uri; - } - - try - { - return new URI(scheme, schemeSpecific, frag); - } - catch (URISyntaxException ex) - { - Logger.getLogger(SVGUniverse.class.getName()).log(Level.SEVERE, null, ex); - } - return null; - } - - /** - * Looks up a href within our universe. If the href refers to a document - * that is not loaded, it will be loaded. The URL #target will then be - * checked against the SVG diagram's index and the corresponding element - * returned. If there is no corresponding index, null is returned. - */ - public SVGElement getElement(URI path, boolean loadIfAbsent) - { - try - { - path = cleanUri(path); - - //Strip fragment from URI - URI xmlBase = new URI(path.getScheme(), path.getSchemeSpecificPart(), null); - - SVGDiagram dia = (SVGDiagram) loadedDocs.get(xmlBase); - if (dia == null && loadIfAbsent) - { -//System.err.println("SVGUnivserse: " + xmlBase.toString()); -//javax.swing.JOptionPane.showMessageDialog(null, xmlBase.toString()); - URL url = xmlBase.toURL(); - - loadSVG(url, false); - dia = (SVGDiagram) loadedDocs.get(xmlBase); - if (dia == null) - { - return null; - } - } - - String fragment = path.getFragment(); - return fragment == null ? dia.getRoot() : dia.getElement(fragment); - } catch (Exception e) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, - "Could not parse path " + path, e); - return null; - } - } - - public SVGDiagram getDiagram(URI xmlBase) - { - return getDiagram(xmlBase, true); - } - - /** - * Returns the diagram that has been loaded from this root. If diagram is - * not already loaded, returns null. - */ - public SVGDiagram getDiagram(URI xmlBase, boolean loadIfAbsent) - { - if (xmlBase == null) - { - return null; - } - - SVGDiagram dia = (SVGDiagram) loadedDocs.get(xmlBase); - if (dia != null || !loadIfAbsent) - { - return dia; - } - - //Load missing diagram - try - { - URL url; - if ("jar".equals(xmlBase.getScheme()) && xmlBase.getPath() != null && !xmlBase.getPath().contains("!/")) - { - //Workaround for resources stored in jars loaded by Webstart. - //http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6753651 - url = SVGUniverse.class.getResource(xmlBase.getPath()); - } - else - { - url = xmlBase.toURL(); - } - - - loadSVG(url, false); - dia = (SVGDiagram) loadedDocs.get(xmlBase); - return dia; - } catch (Exception e) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, - "Could not parse", e); - } - - return null; - } - - /** - * Wraps input stream in a BufferedInputStream. If it is detected that this - * input stream is GZIPped, also wraps in a GZIPInputStream for inflation. - * - * @param is Raw input stream - * @return Uncompressed stream of SVG data - * @throws java.io.IOException - */ - private InputStream createDocumentInputStream(InputStream is) throws IOException - { - BufferedInputStream bin = new BufferedInputStream(is); - bin.mark(2); - int b0 = bin.read(); - int b1 = bin.read(); - bin.reset(); - - //Check for gzip magic number - if ((b1 << 8 | b0) == GZIPInputStream.GZIP_MAGIC) - { - GZIPInputStream iis = new GZIPInputStream(bin); - return iis; - } else - { - //Plain text - return bin; - } - } - - public URI loadSVG(URL docRoot) - { - return loadSVG(docRoot, false); - } - - /** - * Loads an SVG file and all the files it references from the URL provided. - * If a referenced file already exists in the SVG universe, it is not - * reloaded. - * - * @param docRoot - URL to the location where this SVG file can be found. - * @param forceLoad - if true, ignore cached diagram and reload - * @return - The URI that refers to the loaded document - */ - public URI loadSVG(URL docRoot, boolean forceLoad) - { - try - { - URI uri = new URI(docRoot.toString()); - if (loadedDocs.containsKey(uri) && !forceLoad) - { - return uri; - } - - InputStream is = docRoot.openStream(); - URI result = loadSVG(uri, new InputSource(createDocumentInputStream(is))); - is.close(); - return result; - } catch (URISyntaxException ex) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, - "Could not parse", ex); - } catch (IOException e) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, - "Could not parse", e); - } - - return null; - } - - public URI loadSVG(InputStream is, String name) throws IOException - { - return loadSVG(is, name, false); - } - - public URI loadSVG(InputStream is, String name, boolean forceLoad) throws IOException - { - URI uri = getStreamBuiltURI(name); - if (uri == null) - { - return null; - } - if (loadedDocs.containsKey(uri) && !forceLoad) - { - return uri; - } - - return loadSVG(uri, new InputSource(createDocumentInputStream(is))); - } - - public URI loadSVG(Reader reader, String name) - { - return loadSVG(reader, name, false); - } - - /** - * This routine allows you to create SVG documents from data streams that - * may not necessarily have a URL to load from. Since every SVG document - * must be identified by a unique URL, Salamander provides a method to fake - * this for streams by defining it's own protocol - svgSalamander - for SVG - * documents without a formal URL. - * - * @param reader - A stream containing a valid SVG document - * @param name -

A unique name for this document. It will be used to - * construct a unique URI to refer to this document and perform resolution - * with relative URIs within this document.

For example, a name of - * "/myScene" will produce the URI svgSalamander:/myScene. - * "/maps/canada/toronto" will produce svgSalamander:/maps/canada/toronto. - * If this second document then contained the href "../uk/london", it would - * resolve by default to svgSalamander:/maps/uk/london. That is, SVG - * Salamander defines the URI scheme svgSalamander for it's own internal use - * and uses it for uniquely identfying documents loaded by stream.

If - * you need to link to documents outside of this scheme, you can either - * supply full hrefs (eg, href="url(http://www.kitfox.com/index.html)") or - * put the xml:base attribute in a tag to change the defaultbase URIs are - * resolved against

If a name does not start with the character '/', - * it will be automatically prefixed to it.

- * @param forceLoad - if true, ignore cached diagram and reload - * - * @return - The URI that refers to the loaded document - */ - public URI loadSVG(Reader reader, String name, boolean forceLoad) - { -//System.err.println(url.toString()); - //Synthesize URI for this stream - URI uri = getStreamBuiltURI(name); - if (uri == null) - { - return null; - } - if (loadedDocs.containsKey(uri) && !forceLoad) - { - return uri; - } - - return loadSVG(uri, new InputSource(reader)); - } - - /** - * Synthesize a URI for an SVGDiagram constructed from a stream. - * - * @param name - Name given the document constructed from a stream. - */ - public URI getStreamBuiltURI(String name) - { - if (name == null || name.length() == 0) - { - return null; - } - - if (name.charAt(0) != '/') - { - name = '/' + name; - } - - try - { - //Dummy URL for SVG documents built from image streams - return new URI(INPUTSTREAM_SCHEME, name, null); - } catch (Exception e) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, - "Could not parse", e); - return null; - } - } - - static ThreadLocal threadSAXParser = new ThreadLocal(); - - private XMLReader getXMLReader() throws SAXException, ParserConfigurationException - { - SAXParser saxParser = threadSAXParser.get(); - if (saxParser == null) - { - SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); - saxParserFactory.setNamespaceAware(true); - saxParser = saxParserFactory.newSAXParser(); - threadSAXParser.set(saxParser); - } - return saxParser.getXMLReader(); - } - - protected URI loadSVG(URI xmlBase, InputSource is) - { - xmlBase = cleanUri(xmlBase); - - - // Use an instance of ourselves as the SAX event handler - SVGLoader handler = new SVGLoader(xmlBase, this, verbose); - - //Place this docment in the universe before it is completely loaded - // so that the load process can refer to references within it's current - // document - loadedDocs.put(xmlBase, handler.getLoadedDiagram()); - - try - { - // Parse the input - XMLReader reader = getXMLReader(); - reader.setEntityResolver( - new EntityResolver() - { - public InputSource resolveEntity(String publicId, String systemId) - { - //Ignore all DTDs - return new InputSource(new ByteArrayInputStream(new byte[0])); - } - }); - reader.setContentHandler(handler); - reader.parse(is); - - handler.getLoadedDiagram().updateTime(curTime); - return xmlBase; - } catch (SAXParseException sex) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, - "Error processing " + xmlBase, sex); - - loadedDocs.remove(xmlBase); - return null; - } catch (Throwable e) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, - "Could not load SVG " + xmlBase, e); - } - - return null; - } - - /** - * Get list of uris of all loaded documents and subdocuments. - * @return - */ - public ArrayList getLoadedDocumentURIs() - { - return new ArrayList(loadedDocs.keySet()); - } - - /** - * Remove loaded document from cache. - * @param uri - */ - public void removeDocument(URI uri) - { - uri = cleanUri(uri); - loadedDocs.remove(uri); - } - - public boolean isVerbose() - { - return verbose; - } - - public void setVerbose(boolean verbose) - { - this.verbose = verbose; - } - - /** - * Uses serialization to duplicate this universe. - */ - public SVGUniverse duplicate() throws IOException, ClassNotFoundException - { - ByteArrayOutputStream bs = new ByteArrayOutputStream(); - ObjectOutputStream os = new ObjectOutputStream(bs); - os.writeObject(this); - os.close(); - - ByteArrayInputStream bin = new ByteArrayInputStream(bs.toByteArray()); - ObjectInputStream is = new ObjectInputStream(bin); - SVGUniverse universe = (SVGUniverse) is.readObject(); - is.close(); - - return universe; - } - - /** - * @return the imageDataInlineOnly - */ - public boolean isImageDataInlineOnly() - { - return imageDataInlineOnly; - } - - /** - * @param imageDataInlineOnly the imageDataInlineOnly to set - */ - public void setImageDataInlineOnly(boolean imageDataInlineOnly) - { - this.imageDataInlineOnly = imageDataInlineOnly; - } -} --- a/src/com/kitfox/svg/ShapeElement.java +++ /dev/null @@ -1,448 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on January 26, 2004, 5:21 PM - */ - -package com.kitfox.svg; - -import com.kitfox.svg.Marker.MarkerLayout; -import com.kitfox.svg.Marker.MarkerPos; -import com.kitfox.svg.xml.StyleAttribute; -import java.awt.AlphaComposite; -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Composite; -import java.awt.Graphics2D; -import java.awt.Paint; -import java.awt.Shape; -import java.awt.geom.AffineTransform; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; -import java.net.URI; -import java.util.ArrayList; -import java.util.List; - - - -/** - * Parent of shape objects - * - * @author Mark McKay - * @author Mark McKay - */ -abstract public class ShapeElement extends RenderableElement -{ - - /** - * This is necessary to get text elements to render the stroke the correct - * width. It is an alternative to producing new font glyph sets at different - * sizes. - */ - protected float strokeWidthScalar = 1f; - - /** Creates a new instance of ShapeElement */ - public ShapeElement() { - } - - @Override - abstract protected void doRender(java.awt.Graphics2D g) throws SVGException; - - /* - protected void setStrokeWidthScalar(float strokeWidthScalar) - { - this.strokeWidthScalar = strokeWidthScalar; - } - */ - - @Override - protected void doPick(Point2D point, boolean boundingBox, List> retVec) throws SVGException - { -// StyleAttribute styleAttrib = new StyleAttribute(); -// if (getStyle(styleAttrib.setName("fill")) && getShape().contains(point)) - if ((boundingBox ? getBoundingBox() : getShape()).contains(point)) - { - retVec.add(getPath(null)); - } - } - - @Override - protected void doPick(Rectangle2D pickArea, AffineTransform ltw, boolean boundingBox, List> retVec) throws SVGException - { -// StyleAttribute styleAttrib = new StyleAttribute(); -// if (getStyle(styleAttrib.setName("fill")) && getShape().contains(point)) - if (ltw.createTransformedShape((boundingBox ? getBoundingBox() : getShape())).intersects(pickArea)) - { - retVec.add(getPath(null)); - } - } - - private Paint handleCurrentColor(StyleAttribute styleAttrib) throws SVGException - { - if (styleAttrib.getStringValue().equals("currentColor")) - { - StyleAttribute currentColorAttrib = new StyleAttribute(); - if (getStyle(currentColorAttrib.setName("color"))) - { - if (!currentColorAttrib.getStringValue().equals("none")) - { - return currentColorAttrib.getColorValue(); - } - } - return null; - } - else - { - return styleAttrib.getColorValue(); - } - } - - protected void renderShape(Graphics2D g, Shape shape) throws SVGException - { -//g.setColor(Color.green); - - StyleAttribute styleAttrib = new StyleAttribute(); - - //Don't process if not visible - if (getStyle(styleAttrib.setName("visibility"))) - { - if (!styleAttrib.getStringValue().equals("visible")) return; - } - - if (getStyle(styleAttrib.setName("display"))) - { - if (styleAttrib.getStringValue().equals("none")) return; - } - - //None, solid color, gradient, pattern - Paint fillPaint = Color.black; //Default to black. Must be explicitly set to none for no fill. - if (getStyle(styleAttrib.setName("fill"))) - { - if (styleAttrib.getStringValue().equals("none")) fillPaint = null; - else - { - fillPaint = handleCurrentColor(styleAttrib); - if (fillPaint == null) - { - URI uri = styleAttrib.getURIValue(getXMLBase()); - if (uri != null) - { - Rectangle2D bounds = shape.getBounds2D(); - AffineTransform xform = g.getTransform(); - - SVGElement ele = diagram.getUniverse().getElement(uri); - if (ele != null) - { - try { - fillPaint = ((FillElement)ele).getPaint(bounds, xform); - } catch (IllegalArgumentException e) { - throw new SVGException(e); - } - } - } - } - } - } - - //Default opacity - float opacity = 1f; - if (getStyle(styleAttrib.setName("opacity"))) - { - opacity = styleAttrib.getRatioValue(); - } - - float fillOpacity = opacity; - if (getStyle(styleAttrib.setName("fill-opacity"))) - { - fillOpacity *= styleAttrib.getRatioValue(); - } - - - Paint strokePaint = null; //Default is to stroke with none - if (getStyle(styleAttrib.setName("stroke"))) - { - if (styleAttrib.getStringValue().equals("none")) strokePaint = null; - else - { - strokePaint = handleCurrentColor(styleAttrib); - if (strokePaint == null) - { - URI uri = styleAttrib.getURIValue(getXMLBase()); - if (uri != null) - { - Rectangle2D bounds = shape.getBounds2D(); - AffineTransform xform = g.getTransform(); - - SVGElement ele = diagram.getUniverse().getElement(uri); - if (ele != null) - { - strokePaint = ((FillElement)ele).getPaint(bounds, xform); - } - } - } - } - } - - float[] strokeDashArray = null; - if (getStyle(styleAttrib.setName("stroke-dasharray"))) - { - strokeDashArray = styleAttrib.getFloatList(); - if (strokeDashArray.length == 0) strokeDashArray = null; - } - - float strokeDashOffset = 0f; - if (getStyle(styleAttrib.setName("stroke-dashoffset"))) - { - strokeDashOffset = styleAttrib.getFloatValueWithUnits(); - } - - int strokeLinecap = BasicStroke.CAP_BUTT; - if (getStyle(styleAttrib.setName("stroke-linecap"))) - { - String val = styleAttrib.getStringValue(); - if (val.equals("round")) - { - strokeLinecap = BasicStroke.CAP_ROUND; - } - else if (val.equals("square")) - { - strokeLinecap = BasicStroke.CAP_SQUARE; - } - } - - int strokeLinejoin = BasicStroke.JOIN_MITER; - if (getStyle(styleAttrib.setName("stroke-linejoin"))) - { - String val = styleAttrib.getStringValue(); - if (val.equals("round")) - { - strokeLinejoin = BasicStroke.JOIN_ROUND; - } - else if (val.equals("bevel")) - { - strokeLinejoin = BasicStroke.JOIN_BEVEL; - } - } - - float strokeMiterLimit = 4f; - if (getStyle(styleAttrib.setName("stroke-miterlimit"))) - { - strokeMiterLimit = Math.max(styleAttrib.getFloatValueWithUnits(), 1); - } - - float strokeOpacity = opacity; - if (getStyle(styleAttrib.setName("stroke-opacity"))) - { - strokeOpacity *= styleAttrib.getRatioValue(); - } - - float strokeWidth = 1f; - if (getStyle(styleAttrib.setName("stroke-width"))) - { - strokeWidth = styleAttrib.getFloatValueWithUnits(); - } -// if (strokeWidthScalar != 1f) -// { - strokeWidth *= strokeWidthScalar; -// } - - Marker markerStart = null; - if (getStyle(styleAttrib.setName("marker-start"))) - { - if (!styleAttrib.getStringValue().equals("none")) - { - URI uri = styleAttrib.getURIValue(getXMLBase()); - markerStart = (Marker)diagram.getUniverse().getElement(uri); - } - } - - Marker markerMid = null; - if (getStyle(styleAttrib.setName("marker-mid"))) - { - if (!styleAttrib.getStringValue().equals("none")) - { - URI uri = styleAttrib.getURIValue(getXMLBase()); - markerMid = (Marker)diagram.getUniverse().getElement(uri); - } - } - - Marker markerEnd = null; - if (getStyle(styleAttrib.setName("marker-end"))) - { - if (!styleAttrib.getStringValue().equals("none")) - { - URI uri = styleAttrib.getURIValue(getXMLBase()); - markerEnd = (Marker)diagram.getUniverse().getElement(uri); - } - } - - - //Draw the shape - if (fillPaint != null && fillOpacity != 0f) - { - if (fillOpacity <= 0) - { - //Do nothing - } - else if (fillOpacity < 1f) - { - Composite cachedComposite = g.getComposite(); - g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, fillOpacity)); - - g.setPaint(fillPaint); - g.fill(shape); - - g.setComposite(cachedComposite); - } - else - { - g.setPaint(fillPaint); - g.fill(shape); - } - } - - - if (strokePaint != null && strokeOpacity != 0f) - { - BasicStroke stroke; - if (strokeDashArray == null) - { - stroke = new BasicStroke(strokeWidth, strokeLinecap, strokeLinejoin, strokeMiterLimit); - } - else - { - stroke = new BasicStroke(strokeWidth, strokeLinecap, strokeLinejoin, strokeMiterLimit, strokeDashArray, strokeDashOffset); - } - - Shape strokeShape; - AffineTransform cacheXform = g.getTransform(); - if (vectorEffect == VECTOR_EFFECT_NON_SCALING_STROKE) - { - strokeShape = cacheXform.createTransformedShape(shape); - strokeShape = stroke.createStrokedShape(strokeShape); - } - else - { - strokeShape = stroke.createStrokedShape(shape); - } - - if (strokeOpacity <= 0) - { - //Do nothing - } - else - { - Composite cachedComposite = g.getComposite(); - - if (strokeOpacity < 1f) - { - g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, strokeOpacity)); - } - - if (vectorEffect == VECTOR_EFFECT_NON_SCALING_STROKE) - { - //Set to identity - g.setTransform(new AffineTransform()); - } - - g.setPaint(strokePaint); - g.fill(strokeShape); - - if (vectorEffect == VECTOR_EFFECT_NON_SCALING_STROKE) - { - //Set to identity - g.setTransform(cacheXform); - } - - if (strokeOpacity < 1f) - { - g.setComposite(cachedComposite); - } - } - } - - if (markerStart != null || markerMid != null || markerEnd != null) - { - MarkerLayout layout = new MarkerLayout(); - layout.layout(shape); - - ArrayList list = layout.getMarkerList(); - for (int i = 0; i < list.size(); ++i) - { - MarkerPos pos = list.get(i); - - switch (pos.type) - { - case Marker.MARKER_START: - if (markerStart != null) - { - markerStart.render(g, pos, strokeWidth); - } - break; - case Marker.MARKER_MID: - if (markerMid != null) - { - markerMid.render(g, pos, strokeWidth); - } - break; - case Marker.MARKER_END: - if (markerEnd != null) - { - markerEnd.render(g, pos, strokeWidth); - } - break; - } - } - } - } - - abstract public Shape getShape(); - - protected Rectangle2D includeStrokeInBounds(Rectangle2D rect) throws SVGException - { - StyleAttribute styleAttrib = new StyleAttribute(); - if (!getStyle(styleAttrib.setName("stroke"))) return rect; - - double strokeWidth = 1; - if (getStyle(styleAttrib.setName("stroke-width"))) strokeWidth = styleAttrib.getDoubleValue(); - - rect.setRect( - rect.getX() - strokeWidth / 2, - rect.getY() - strokeWidth / 2, - rect.getWidth() + strokeWidth, - rect.getHeight() + strokeWidth); - - return rect; - } - -} --- a/src/com/kitfox/svg/Stop.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on January 26, 2004, 1:56 AM - */ -package com.kitfox.svg; - -import com.kitfox.svg.xml.StyleAttribute; -import java.awt.Color; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class Stop extends SVGElement -{ - - public static final String TAG_NAME = "stop"; - float offset = 0f; - float opacity = 1f; - Color color = Color.black; - - /** - * Creates a new instance of Stop - */ - public Stop() - { - } - - @Override - public String getTagName() - { - return TAG_NAME; - } - - @Override - protected void build() throws SVGException - { - super.build(); - - StyleAttribute sty = new StyleAttribute(); - - if (getPres(sty.setName("offset"))) - { - offset = sty.getFloatValue(); - String units = sty.getUnits(); - if (units != null && units.equals("%")) - { - offset /= 100f; - } - if (offset > 1) - { - offset = 1; - } - if (offset < 0) - { - offset = 0; - } - } - - if (getStyle(sty.setName("stop-color"))) - { - color = sty.getColorValue(); - } - - if (getStyle(sty.setName("stop-opacity"))) - { - opacity = sty.getRatioValue(); - } - } - - /** - * Updates all attributes in this diagram associated with a time event. Ie, - * all attributes with track information. - * - * @return - true if this node has changed state as a result of the time - * update - */ - @Override - public boolean updateTime(double curTime) throws SVGException - { -// if (trackManager.getNumTracks() == 0) return false; - - //Get current values for parameters - StyleAttribute sty = new StyleAttribute(); - boolean shapeChange = false; - - if (getPres(sty.setName("offset"))) - { - float newVal = sty.getFloatValue(); - if (newVal != offset) - { - offset = newVal; - shapeChange = true; - } - } - - if (getStyle(sty.setName("stop-color"))) - { - Color newVal = sty.getColorValue(); - if (newVal != color) - { - color = newVal; - shapeChange = true; - } - } - - if (getStyle(sty.setName("stop-opacity"))) - { - float newVal = sty.getFloatValue(); - if (newVal != opacity) - { - opacity = newVal; - shapeChange = true; - } - } - - return shapeChange; - } -} --- a/src/com/kitfox/svg/Style.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on September 19, 2004, 1:56 AM - */ -package com.kitfox.svg; - -import com.kitfox.svg.xml.StyleAttribute; -import com.kitfox.svg.xml.StyleSheet; - -/** - * Holds title textual information within tree - * - * @author Mark McKay - * @author Mark McKay - */ -public class Style extends SVGElement -{ - - public static final String TAG_NAME = "style"; - //Should be set to "text/css" - String type; - StringBuffer text = new StringBuffer(); - - StyleSheet styleSheet; - - /** - * Creates a new instance of Stop - */ - public Style() - { - } - - @Override - public String getTagName() - { - return TAG_NAME; - } - - /** - * Called during load process to add text scanned within a tag - */ - @Override - public void loaderAddText(SVGLoaderHelper helper, String text) - { - this.text.append(text); - - //Invalidate style sheet - styleSheet = null; - } - - @Override - protected void build() throws SVGException - { - super.build(); - - StyleAttribute sty = new StyleAttribute(); - - if (getPres(sty.setName("type"))) - { - type = sty.getStringValue(); - } - } - - @Override - public boolean updateTime(double curTime) throws SVGException - { - //Style sheet doesn't change - return false; - } - - public StyleSheet getStyleSheet() - { - if (styleSheet == null && text.length() > 0) - { - styleSheet = StyleSheet.parseSheet(text.toString()); - } - return styleSheet; - } -} --- a/src/com/kitfox/svg/Symbol.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on January 26, 2004, 1:56 AM - */ -package com.kitfox.svg; - -import com.kitfox.svg.xml.StyleAttribute; -import java.awt.Graphics2D; -import java.awt.Rectangle; -import java.awt.Shape; -import java.awt.geom.AffineTransform; -import java.awt.geom.Rectangle2D; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class Symbol extends Group -{ - - public static final String TAG_NAME = "symbol"; - AffineTransform viewXform; - Rectangle2D viewBox; - - /** - * Creates a new instance of Stop - */ - public Symbol() - { - } - - @Override - public String getTagName() - { - return TAG_NAME; - } - - @Override - protected void build() throws SVGException - { - super.build(); - - StyleAttribute sty = new StyleAttribute(); - -// sty = getPres("unicode"); -// if (sty != null) unicode = sty.getStringValue(); - - - if (getPres(sty.setName("viewBox"))) - { - float[] dim = sty.getFloatList(); - viewBox = new Rectangle2D.Float(dim[0], dim[1], dim[2], dim[3]); - } - - if (viewBox == null) - { -// viewBox = super.getBoundingBox(); - viewBox = new Rectangle(0, 0, 1, 1); - } - - //Transform pattern onto unit square - viewXform = new AffineTransform(); - viewXform.scale(1.0 / viewBox.getWidth(), 1.0 / viewBox.getHeight()); - viewXform.translate(-viewBox.getX(), -viewBox.getY()); - } - - @Override - protected boolean outsideClip(Graphics2D g) throws SVGException - { - Shape clip = g.getClip(); -// g.getClipBounds(clipBounds); - Rectangle2D rect = super.getBoundingBox(); - if (clip == null || clip.intersects(rect)) - { - return false; - } - - return true; - - } - - @Override - protected void doRender(Graphics2D g) throws SVGException - { - AffineTransform oldXform = g.getTransform(); - g.transform(viewXform); - - super.doRender(g); - - g.setTransform(oldXform); - } - - @Override - public Shape getShape() - { - Shape shape = super.getShape(); - return viewXform.createTransformedShape(shape); - } - - @Override - public Rectangle2D getBoundingBox() throws SVGException - { - Rectangle2D rect = super.getBoundingBox(); - return viewXform.createTransformedShape(rect).getBounds2D(); - } - - /** - * Updates all attributes in this diagram associated with a time event. Ie, - * all attributes with track information. - * - * @return - true if this node has changed state as a result of the time - * update - */ - @Override - public boolean updateTime(double curTime) throws SVGException - { -// if (trackManager.getNumTracks() == 0) return false; - boolean changeState = super.updateTime(curTime); - - //View box properties do not change - - return changeState; - } -} --- a/src/com/kitfox/svg/Text.java +++ /dev/null @@ -1,216 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on January 26, 2004, 1:56 AM - */ -package com.kitfox.svg; - -import com.kitfox.svg.util.FontUtil; -import com.kitfox.svg.xml.StyleAttribute; - -import java.awt.geom.AffineTransform; -import java.awt.geom.Path2D; -import java.awt.geom.Rectangle2D; -import java.util.Arrays; -import java.util.List; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class Text extends Tspan -{ - public static final String TAG_NAME = "text"; - - public static final int TXAN_START = 0; - public static final int TXAN_MIDDLE = 1; - public static final int TXAN_END = 2; - public static final int TXST_NORMAL = 0; - public static final int TXST_ITALIC = 1; - public static final int TXST_OBLIQUE = 2; - public static final int TXWE_NORMAL = 0; - public static final int TXWE_BOLD = 1; - public static final int TXWE_BOLDER = 2; - public static final int TXWE_LIGHTER = 3; - public static final int TXWE_100 = 4; - public static final int TXWE_200 = 5; - public static final int TXWE_300 = 6; - public static final int TXWE_400 = 7; - public static final int TXWE_500 = 8; - public static final int TXWE_600 = 9; - public static final int TXWE_700 = 10; - public static final int TXWE_800 = 11; - public static final int TXWE_900 = 12; - - int textAnchor = TXAN_START; - - /** - * Creates a new instance of Stop - */ - public Text() - { - } - - @Override - public String getTagName() - { - return TAG_NAME; - } - - /** - * Discard cached information - */ - public void rebuild() throws SVGException - { - build(); - } - - @Override - protected void build() throws SVGException - { - super.build(); - buildText(); - } - - protected void buildAttributes(StyleAttribute sty) throws SVGException - { - super.buildAttributes(sty); - if (getStyle(sty.setName("text-anchor"))) - { - String s = sty.getStringValue(); - if (s.equals("middle")) - { - textAnchor = TXAN_MIDDLE; - } else if (s.equals("end")) - { - textAnchor = TXAN_END; - } else - { - textAnchor = TXAN_START; - } - } else - { - textAnchor = TXAN_START; - } - } - - - private void buildText() throws SVGException - { - buildShapeInformation(); - Cursor cursor = createInitialCursor(); - float xInitial = cursor.x; - super.buildTextShape(cursor); - alignSegmentsAtAnchor(fullPath, xInitial); - } - - private void alignSegmentsAtAnchor(Path2D textPath, float xInitial) - { - AffineTransform tx; - Rectangle2D bounds; - switch (textAnchor) - { - case TXAN_MIDDLE: - bounds = textPath.getBounds2D(); - tx = AffineTransform.getTranslateInstance( - -(bounds.getX() + bounds.getWidth() / 2.0 - xInitial), 0 - ); - break; - case TXAN_END: - bounds = textPath.getBounds2D(); - tx = AffineTransform.getTranslateInstance( - -(bounds.getX() + bounds.getWidth() - xInitial), 0 - ); - break; - default: - tx = null; - break; - } - if (tx != null) - { - fullPath.transform(tx); - textBounds = fullPath.getBounds2D(); - transformSegments(segments, tx); - } - } - - private void transformSegments(List segments, AffineTransform transform) - { - for (TextSegment segment : segments) - { - if (segment.textPath != null) - { - segment.textPath.transform(transform); - } else - { - segment.element.fullPath.transform(transform); - segment.element.textBounds = segment.element.fullPath.getBounds2D(); - transformSegments(segment.element.segments, transform); - } - } - } - - /** - * Updates all attributes in this diagram associated with a time event. Ie, - * all attributes with track information. - * - * @return - true if this node has changed state as a result of the time - * update - */ - @Override - public boolean updateTime(double curTime) throws SVGException - { - boolean changeState = super.updateTime(curTime); - - //Get current values for parameters - FontUtil.FontInfo fontInfoOld = fontInfo; - float[] xOld = x; - float[] yOld = y; - float[] dxOld = dx; - float[] dyOld = dy; - buildShapeInformation(); - - boolean shapeChange = !fontInfo.equals(fontInfoOld) - || !Arrays.equals(xOld, x) - || !Arrays.equals(yOld, y) - || !Arrays.equals(dxOld, dx) - || !Arrays.equals(dyOld, dy); - - if (shapeChange) - { - buildText(); - } - - return changeState || shapeChange; - } -} --- a/src/com/kitfox/svg/Title.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on September 19, 2004, 1:56 AM - */ -package com.kitfox.svg; - -/** - * Holds title textual information within tree - * - * @author Mark McKay - * @author Mark McKay - */ -public class Title extends SVGElement -{ - public static final String TAG_NAME = "title"; - - StringBuffer text = new StringBuffer(); - - /** - * Creates a new instance of Stop - */ - public Title() - { - } - - @Override - public String getTagName() - { - return TAG_NAME; - } - - /** - * Called during load process to add text scanned within a tag - */ - @Override - public void loaderAddText(SVGLoaderHelper helper, String text) - { - this.text.append(text); - } - - public String getText() - { - return text.toString(); - } - - /** - * Updates all attributes in this diagram associated with a time event. Ie, - * all attributes with track information. - * - * @return - true if this node has changed state as a result of the time - * update - */ - @Override - public boolean updateTime(double curTime) throws SVGException - { - //Title does not change - return false; - } -} --- a/src/com/kitfox/svg/TransformableElement.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on January 26, 2004, 9:00 AM - */ -package com.kitfox.svg; - -import com.kitfox.svg.xml.StyleAttribute; -import java.awt.Shape; -import java.awt.geom.AffineTransform; -import java.awt.geom.Rectangle2D; - -/** - * Maintains bounding box for this element - * - * @author Mark McKay - * @author Mark McKay - */ -abstract public class TransformableElement extends SVGElement -{ - AffineTransform xform = null; - - /** - * Creates a new instance of BoundedElement - */ - public TransformableElement() - { - } - - public TransformableElement(String id, SVGElement parent) - { - super(id, parent); - } - - /** - * Fetches a copy of the cached AffineTransform. Note that this value will - * only be valid after the node has been updated. - * - * @return - */ - public AffineTransform getXForm() - { - return xform == null ? null : new AffineTransform(xform); - } - /* - public void loaderStartElement(SVGLoaderHelper helper, Attributes attrs, SVGElement parent) - { - //Load style string - super.loaderStartElement(helper, attrs, parent); - - String transform = attrs.getValue("transform"); - if (transform != null) - { - xform = parseTransform(transform); - } - } - */ - - @Override - protected void build() throws SVGException - { - super.build(); - - StyleAttribute sty = new StyleAttribute(); - - if (getPres(sty.setName("transform"))) - { - xform = parseTransform(sty.getStringValue()); - } - } - - protected Shape shapeToParent(Shape shape) - { - if (xform == null) - { - return shape; - } - return xform.createTransformedShape(shape); - } - - protected Rectangle2D boundsToParent(Rectangle2D rect) - { - if (xform == null || rect == null) - { - return rect; - } - return xform.createTransformedShape(rect).getBounds2D(); - } - - /** - * Updates all attributes in this diagram associated with a time event. Ie, - * all attributes with track information. - * - * @return - true if this node has changed state as a result of the time - * update - */ - @Override - public boolean updateTime(double curTime) throws SVGException - { - StyleAttribute sty = new StyleAttribute(); - - if (getPres(sty.setName("transform"))) - { - AffineTransform newXform = parseTransform(sty.getStringValue()); - if (!newXform.equals(xform)) - { - xform = newXform; - return true; - } - } - - return false; - } -} --- a/src/com/kitfox/svg/Tspan.java +++ /dev/null @@ -1,395 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on January 26, 2004, 1:56 AM - */ -package com.kitfox.svg; - -import com.kitfox.svg.util.FontUtil; -import com.kitfox.svg.xml.StyleAttribute; -import java.awt.Graphics2D; -import java.awt.Shape; -import java.awt.geom.AffineTransform; -import java.awt.geom.GeneralPath; -import java.awt.geom.Path2D; -import java.awt.geom.Rectangle2D; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class Tspan extends ShapeElement -{ - - public static final String TAG_NAME = "tspan"; - float[] x = null; - float[] y = null; - float[] dx = null; - float[] dy = null; - float[] rotate = null; - - float textLength = -1; - String lengthAdjust = "spacing"; - - // List of strings and tspans containing the content of this node - private final List content = new ArrayList<>(); - protected final ArrayList segments = new ArrayList<>(); - protected Rectangle2D textBounds; - protected Path2D fullPath; - - protected FontUtil.FontInfo fontInfo; - private Font font; - - /** - * Creates a new instance of Tspan - */ - public Tspan() - { - } - - @Override - public String getTagName() - { - return TAG_NAME; - } - - /** - * Called after the start element but before the end element to indicate - * each child tag that has been processed - */ - @Override - public void loaderAddChild(SVGLoaderHelper helper, SVGElement child) throws SVGElementException - { - super.loaderAddChild(helper, child); - - content.add(child); - } - - /** - * Called during load process to add text scanned within a tag - */ - @Override - public void loaderAddText(SVGLoaderHelper helper, String text) - { - Matcher matchWs = Pattern.compile("\\s*").matcher(text); - if (!matchWs.matches()) - { - content.add(text); - } - } - - public List getContent() - { - return content; - } - - /** - * Removes all strings and Tspan elements that are children of this element. - */ - public void clearContent() - { - content.clear(); - } - - public void appendText(String text) - { - content.add(text); - } - - public void appendTspan(Tspan tspan) throws SVGElementException - { - super.loaderAddChild(null, tspan); - content.add(tspan); - } - - protected void buildAttributes(StyleAttribute sty) throws SVGException - { - if (getPres(sty.setName("x"))) - { - x = sty.getFloatListWithUnits(); - } - - if (getPres(sty.setName("y"))) - { - y = sty.getFloatListWithUnits(); - } - - if (getPres(sty.setName("dx"))) - { - dx = sty.getFloatListWithUnits(); - } - - if (getPres(sty.setName("dy"))) - { - dy = sty.getFloatListWithUnits(); - } - - if (getPres(sty.setName("rotate"))) - { - rotate = sty.getFloatList(); - for (int i = 0; i < this.rotate.length; i++) - { - rotate[i] = (float) Math.toRadians(this.rotate[i]); - } - } - - if (getStyle(sty.setName("textLength"))) - { - textLength = sty.getFloatValueWithUnits(); - } - else - { - textLength = -1; - } - - if (getStyle(sty.setName("lengthAdjust"))) - { - lengthAdjust = sty.getStringValue(); - } - else - { - lengthAdjust = "spacing"; - } - } - - protected void buildShapeInformation() throws SVGException - { - StyleAttribute sty = new StyleAttribute(); - buildAttributes(sty); - - fontInfo = FontUtil.parseFontInfo(this, sty); - font = FontUtil.getFont(fontInfo, diagram); - } - - protected void buildTextShape(Cursor cursor) throws SVGException - { - buildShapeInformation(); - - fullPath = new GeneralPath(); - - segments.clear(); - segments.ensureCapacity(content.size()); - int currentCursorOffset = cursor.offset; - cursor.offset = 0; - - AffineTransform transform = new AffineTransform(); - - float spaceAdvance = font.getGlyph(" ").getHorizAdvX(); - - for (Serializable obj : content) - { - if (obj instanceof String) - { - String text = ((String) obj); - String trimmed = text.trim(); - if (!text.isEmpty() && text.charAt(0) <= ' ') - cursor.x += font.getGlyph(" ").getHorizAdvX(); - Path2D textPath = createStringSegmentPath(trimmed, font, cursor, transform); - if (!text.isEmpty() && text.charAt(text.length() - 1) <= ' ') - cursor.x += spaceAdvance; - - fullPath.append(textPath, false); - segments.add(new TextSegment(textPath, this)); - } else if (obj instanceof Tspan) - { - Tspan tspan = (Tspan) obj; - tspan.buildTextShape(cursor); - fullPath.append(tspan.fullPath, false); - segments.add(new TextSegment(null, (Tspan) obj)); - } - } - - textBounds = fullPath.getBounds2D(); - cursor.offset += currentCursorOffset; - } - - private Path2D createStringSegmentPath(String text, Font font, Cursor cursor, AffineTransform xform) - { - Path2D textPath = new GeneralPath(); - - for (int i = 0; i < text.length(); i++) - { - // The positions are specified for the whole recursive content of a span. - // We need to account for any eventual text which occurred before. - cursor.x = getXCursorForIndex(cursor.x, cursor.offset + i); - cursor.y = getYCursorForIndex(cursor.y, cursor.offset + i); - - xform.setToTranslation(cursor.x, cursor.y); - if (rotate != null && cursor.offset + i < rotate.length) - { - xform.rotate(rotate[cursor.offset + i]); - } - - String unicode = text.substring(i, i + 1); - MissingGlyph glyph = font.getGlyph(unicode); - - Shape path = glyph.getPath(); - if (path != null) - { - path = xform.createTransformedShape(path); - textPath.append(path, false); - } - cursor.x += glyph.getHorizAdvX() + fontInfo.letterSpacing; - } - cursor.offset += text.length(); - - strokeWidthScalar = 1f; - return textPath; - } - - protected Cursor createInitialCursor() - { - return new Cursor(getXCursorForIndex(0, 0), - getYCursorForIndex(0, 0)); - } - - private float getXCursorForIndex(float current, int index) - { - return getCursorForIndex(current, index, x, dx); - } - - private float getYCursorForIndex(float current, int index) - { - return getCursorForIndex(current, index, y, dy); - } - - private float getCursorForIndex(float current, int index, float[] absolutes, float[] deltas) - { - if (absolutes != null && index < absolutes.length) - { - current = absolutes[index]; - } else if (deltas != null && index < deltas.length) - { - current += deltas[index]; - } - return current; - } - - @Override - protected void doRender(Graphics2D g) throws SVGException - { - beginLayer(g); - for (TextSegment segment : segments) { - if (segment.textPath != null) - { - // Text portion of this span. - segment.element.renderShape(g, segment.textPath); - } else - { - // Child span. - segment.element.doRender(g); - } - } - finishLayer(g); - } - - @Override - public Shape getShape() - { - return shapeToParent(fullPath); - } - - @Override - public Rectangle2D getBoundingBox() - { - return boundsToParent(textBounds); - } - - /** - * Updates all attributes in this diagram associated with a time event. Ie, - * all attributes with track information. - * - * @return - true if this node has changed state as a result of the time - * update - */ - @Override - public boolean updateTime(double curTime) throws SVGException - { - //Tspan does not change - return false; - } - - public String getText() - { - return getText(new StringBuilder()); - } - - private String getText(StringBuilder builder) - { - for (Serializable serializable : content) - { - if (serializable instanceof Tspan) - { - ((Tspan) serializable).getText(builder); - builder.append(' '); - } else if (serializable != null) - { - builder.append(serializable).append(' '); - } - } - if (builder.length() > 0) - { - // Remove trailing space. - return builder.substring(0, builder.length() - 1); - } else - { - return ""; - } - } - - protected static class TextSegment { - final Path2D textPath; - final Tspan element; - - private TextSegment(Path2D textPath, Tspan element) { - this.textPath = textPath; - this.element = element; - } - } - - protected static class Cursor { - float x; - float y; - int offset; - - public Cursor(float x, float y) { - this.x = x; - this.y = y; - } - } -} --- a/src/com/kitfox/svg/Use.java +++ /dev/null @@ -1,264 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on January 26, 2004, 1:54 AM - */ -package com.kitfox.svg; - -import com.kitfox.svg.xml.StyleAttribute; -import java.awt.Graphics2D; -import java.awt.Shape; -import java.awt.geom.AffineTransform; -import java.awt.geom.Rectangle2D; -import java.net.URI; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class Use extends ShapeElement -{ - public static final String TAG_NAME = "use"; - - float x = 0f; - float y = 0f; - float width = 1f; - float height = 1f; -// SVGElement href = null; - URI href = null; - AffineTransform refXform; - - /** - * Creates a new instance of LinearGradient - */ - public Use() - { - } - - @Override - public String getTagName() - { - return TAG_NAME; - } - - @Override - protected void build() throws SVGException - { - super.build(); - - StyleAttribute sty = new StyleAttribute(); - - if (getPres(sty.setName("x"))) - { - x = sty.getFloatValueWithUnits(); - } - - if (getPres(sty.setName("y"))) - { - y = sty.getFloatValueWithUnits(); - } - - if (getPres(sty.setName("width"))) - { - width = sty.getFloatValueWithUnits(); - } - - if (getPres(sty.setName("height"))) - { - height = sty.getFloatValueWithUnits(); - } - - if (getPres(sty.setName("xlink:href"))) - { - URI src = sty.getURIValue(getXMLBase()); - href = src; -// href = diagram.getUniverse().getElement(src); - } - - //Determine use offset/scale - refXform = new AffineTransform(); - refXform.translate(this.x, this.y); - } - - @Override - protected void doRender(Graphics2D g) throws SVGException - { - beginLayer(g); - - //AffineTransform oldXform = g.getTransform(); - AffineTransform oldXform = g.getTransform(); - g.transform(refXform); - - SVGElement ref = diagram.getUniverse().getElement(href); - - if (ref == null || !(ref instanceof RenderableElement)) - { - return; - } - - RenderableElement rendEle = (RenderableElement)ref; - rendEle.pushParentContext(this); - rendEle.render(g); - rendEle.popParentContext(); - - g.setTransform(oldXform); - - finishLayer(g); - } - - @Override - public Shape getShape() - { - SVGElement ref = diagram.getUniverse().getElement(href); - if (ref instanceof ShapeElement) - { - Shape shape = ((ShapeElement) ref).getShape(); - shape = refXform.createTransformedShape(shape); - shape = shapeToParent(shape); - return shape; - } - - return null; - } - - @Override - public Rectangle2D getBoundingBox() throws SVGException - { - SVGElement ref = diagram.getUniverse().getElement(href); - if (ref instanceof ShapeElement) - { - ShapeElement shapeEle = (ShapeElement) ref; - shapeEle.pushParentContext(this); - Rectangle2D bounds = shapeEle.getBoundingBox(); - shapeEle.popParentContext(); - - bounds = refXform.createTransformedShape(bounds).getBounds2D(); - bounds = boundsToParent(bounds); - - return bounds; - } - - return null; - } - - /** - * Updates all attributes in this diagram associated with a time event. Ie, - * all attributes with track information. - * - * @return - true if this node has changed state as a result of the time - * update - */ - @Override - public boolean updateTime(double curTime) throws SVGException - { -// if (trackManager.getNumTracks() == 0) return false; - boolean changeState = super.updateTime(curTime); - - //Get current values for parameters - StyleAttribute sty = new StyleAttribute(); - boolean shapeChange = false; - - if (getPres(sty.setName("x"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != x) - { - x = newVal; - shapeChange = true; - } - } - - if (getPres(sty.setName("y"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != y) - { - y = newVal; - shapeChange = true; - } - } - - if (getPres(sty.setName("width"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != width) - { - width = newVal; - shapeChange = true; - } - } - - if (getPres(sty.setName("height"))) - { - float newVal = sty.getFloatValueWithUnits(); - if (newVal != height) - { - height = newVal; - shapeChange = true; - } - } - - if (getPres(sty.setName("xlink:href"))) - { - URI src = sty.getURIValue(getXMLBase()); -// SVGElement newVal = diagram.getUniverse().getElement(src); - if (!src.equals(href)) - { - href = src; - shapeChange = true; - } - } - /* - if (getPres(sty.setName("xlink:href"))) - { - URI src = sty.getURIValue(getXMLBase()); - href = diagram.getUniverse().getElement(src); - } - - //Determine use offset/scale - refXform = new AffineTransform(); - refXform.translate(this.x, this.y); - refXform.scale(this.width, this.height); - */ - if (shapeChange) - { - build(); - //Determine use offset/scale -// refXform.setToTranslation(this.x, this.y); -// refXform.scale(this.width, this.height); -// return true; - } - - return changeState || shapeChange; - } -} --- a/src/com/kitfox/svg/animation/Animate.java +++ /dev/null @@ -1,585 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on August 15, 2004, 2:51 AM - */ - -package com.kitfox.svg.animation; - -import com.kitfox.svg.SVGConst; -import com.kitfox.svg.SVGElement; -import com.kitfox.svg.SVGException; -import com.kitfox.svg.SVGLoaderHelper; -import com.kitfox.svg.animation.parser.AnimTimeParser; -import com.kitfox.svg.xml.ColorTable; -import com.kitfox.svg.xml.StyleAttribute; -import com.kitfox.svg.xml.XMLParseUtil; -import java.awt.Color; -import java.awt.geom.AffineTransform; -import java.awt.geom.GeneralPath; -import java.awt.geom.PathIterator; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.xml.sax.Attributes; -import org.xml.sax.SAXException; - - -/** - * Animate is a really annoying morphic tag that could represent a real value, - * a color or a path - * - * @author Mark McKay - * @author Mark McKay - */ -public class Animate extends AnimateBase implements AnimateColorIface -{ - public static final String TAG_NAME = "animate"; - -// StyleAttribute retAttrib = new StyleAttribute - public static final int DT_REAL = 0; - public static final int DT_COLOR = 1; - public static final int DT_PATH = 2; - int dataType = DT_REAL; - - private double fromValue = Double.NaN; - private double toValue = Double.NaN; - private double byValue = Double.NaN; - private double[] valuesValue; - - private Color fromColor = null; - private Color toColor = null; - - private GeneralPath fromPath = null; - private GeneralPath toPath = null; - - /** Creates a new instance of Animate */ - public Animate() - { - } - - @Override - public String getTagName() - { - return TAG_NAME; - } - - public int getDataType() - { - return dataType; - } - - @Override - public void loaderStartElement(SVGLoaderHelper helper, Attributes attrs, SVGElement parent) throws SAXException - { - //Load style string - super.loaderStartElement(helper, attrs, parent); - - String strn = attrs.getValue("from"); - if (strn != null) - { - if (XMLParseUtil.isDouble(strn)) - { - fromValue = XMLParseUtil.parseDouble(strn); - } -// else if (attrs.getValue("attributeName").equals("d")) -// { -// fromPath = this.buildPath(strn, GeneralPath.WIND_EVEN_ODD); -// dataType = DT_PATH; -// } - else - { - fromColor = ColorTable.parseColor(strn); - if (fromColor == null) - { - //Try path - fromPath = this.buildPath(strn, GeneralPath.WIND_EVEN_ODD); - dataType = DT_PATH; - } - else dataType = DT_COLOR; - } - } - - strn = attrs.getValue("to"); - if (strn != null) - { - if (XMLParseUtil.isDouble(strn)) - { - toValue = XMLParseUtil.parseDouble(strn); - } - else - { - toColor = ColorTable.parseColor(strn); - if (toColor == null) - { - //Try path - toPath = this.buildPath(strn, GeneralPath.WIND_EVEN_ODD); - dataType = DT_PATH; - } - else dataType = DT_COLOR; - } - } - - strn = attrs.getValue("by"); - try - { - if (strn != null) byValue = XMLParseUtil.parseDouble(strn); - } catch (Exception e) {} - - strn = attrs.getValue("values"); - try - { - if (strn != null) valuesValue = XMLParseUtil.parseDoubleList(strn); - } catch (Exception e) {} - } - - /** - * Evaluates this animation element for the passed interpolation time. Interp - * must be on [0..1]. - */ - public double eval(double interp) - { - boolean fromExists = !Double.isNaN(fromValue); - boolean toExists = !Double.isNaN(toValue); - boolean byExists = !Double.isNaN(byValue); - boolean valuesExists = valuesValue != null; - - if (valuesExists) - { - double sp = interp * valuesValue.length; - int ip = (int)sp; - double fp = sp - ip; - - int i0 = ip; - int i1 = ip + 1; - - if (i0 < 0) return valuesValue[0]; - if (i1 >= valuesValue.length) return valuesValue[valuesValue.length - 1]; - return valuesValue[i0] * (1 - fp) + valuesValue[i1] * fp; - } - else if (fromExists && toExists) - { - return toValue * interp + fromValue * (1.0 - interp); - } - else if (fromExists && byExists) - { - return fromValue + byValue * interp; - } - else if (toExists && byExists) - { - return toValue - byValue * (1.0 - interp); - } - else if (byExists) - { - return byValue * interp; - } - else if (toExists) - { - StyleAttribute style = new StyleAttribute(getAttribName()); - try - { - getParent().getStyle(style, true, false); - } - catch (SVGException ex) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, - "Could not get from value", ex); - } - double from = style.getDoubleValue(); - return toValue * interp + from * (1.0 - interp); - } - - //Should not reach this line - throw new RuntimeException("Animate tag could not be evalutated - insufficient arguements"); - } - - public Color evalColor(double interp) - { - if (fromColor == null && toColor != null) - { - float[] toCol = new float[3]; - toColor.getColorComponents(toCol); - return new Color(toCol[0] * (float)interp, - toCol[1] * (float)interp, - toCol[2] * (float)interp); - } - else if (fromColor != null && toColor != null) - { - float nInterp = 1 - (float)interp; - - float[] fromCol = new float[3]; - float[] toCol = new float[3]; - fromColor.getColorComponents(fromCol); - toColor.getColorComponents(toCol); - return new Color(fromCol[0] * nInterp + toCol[0] * (float)interp, - fromCol[1] * nInterp + toCol[1] * (float)interp, - fromCol[2] * nInterp + toCol[2] * (float)interp); - } - - throw new RuntimeException("Animate tag could not be evalutated - insufficient arguements"); - } - - public GeneralPath evalPath(double interp) - { - if (fromPath == null && toPath != null) - { - PathIterator itTo = toPath.getPathIterator(new AffineTransform()); - - GeneralPath midPath = new GeneralPath(); - float[] coordsTo = new float[6]; - - for (; !itTo.isDone(); itTo.next()) - { - int segTo = itTo.currentSegment(coordsTo); - - switch (segTo) - { - case PathIterator.SEG_CLOSE: - midPath.closePath(); - break; - case PathIterator.SEG_CUBICTO: - midPath.curveTo( - (float)(coordsTo[0] * interp), - (float)(coordsTo[1] * interp), - (float)(coordsTo[2] * interp), - (float)(coordsTo[3] * interp), - (float)(coordsTo[4] * interp), - (float)(coordsTo[5] * interp) - ); - break; - case PathIterator.SEG_LINETO: - midPath.lineTo( - (float)(coordsTo[0] * interp), - (float)(coordsTo[1] * interp) - ); - break; - case PathIterator.SEG_MOVETO: - midPath.moveTo( - (float)(coordsTo[0] * interp), - (float)(coordsTo[1] * interp) - ); - break; - case PathIterator.SEG_QUADTO: - midPath.quadTo( - (float)(coordsTo[0] * interp), - (float)(coordsTo[1] * interp), - (float)(coordsTo[2] * interp), - (float)(coordsTo[3] * interp) - ); - break; - } - } - - return midPath; - } - else if (toPath != null) - { - PathIterator itFrom = fromPath.getPathIterator(new AffineTransform()); - PathIterator itTo = toPath.getPathIterator(new AffineTransform()); - - GeneralPath midPath = new GeneralPath(); - float[] coordsFrom = new float[6]; - float[] coordsTo = new float[6]; - - for (; !itFrom.isDone(); itFrom.next(), itTo.next()) - { - int segFrom = itFrom.currentSegment(coordsFrom); - int segTo = itTo.currentSegment(coordsTo); - - if (segFrom != segTo) - { - throw new RuntimeException("Path shape mismatch"); - } - - switch (segFrom) - { - case PathIterator.SEG_CLOSE: - midPath.closePath(); - break; - case PathIterator.SEG_CUBICTO: - midPath.curveTo( - (float)(coordsFrom[0] * (1 - interp) + coordsTo[0] * interp), - (float)(coordsFrom[1] * (1 - interp) + coordsTo[1] * interp), - (float)(coordsFrom[2] * (1 - interp) + coordsTo[2] * interp), - (float)(coordsFrom[3] * (1 - interp) + coordsTo[3] * interp), - (float)(coordsFrom[4] * (1 - interp) + coordsTo[4] * interp), - (float)(coordsFrom[5] * (1 - interp) + coordsTo[5] * interp) - ); - break; - case PathIterator.SEG_LINETO: - midPath.lineTo( - (float)(coordsFrom[0] * (1 - interp) + coordsTo[0] * interp), - (float)(coordsFrom[1] * (1 - interp) + coordsTo[1] * interp) - ); - break; - case PathIterator.SEG_MOVETO: - midPath.moveTo( - (float)(coordsFrom[0] * (1 - interp) + coordsTo[0] * interp), - (float)(coordsFrom[1] * (1 - interp) + coordsTo[1] * interp) - ); - break; - case PathIterator.SEG_QUADTO: - midPath.quadTo( - (float)(coordsFrom[0] * (1 - interp) + coordsTo[0] * interp), - (float)(coordsFrom[1] * (1 - interp) + coordsTo[1] * interp), - (float)(coordsFrom[2] * (1 - interp) + coordsTo[2] * interp), - (float)(coordsFrom[3] * (1 - interp) + coordsTo[3] * interp) - ); - break; - } - } - - return midPath; - } - - throw new RuntimeException("Animate tag could not be evalutated - insufficient arguements"); - } - - /** - * If this element is being accumulated, detemine the delta to accumulate by - */ - public double repeatSkipSize(int reps) - { - boolean fromExists = !Double.isNaN(fromValue); - boolean toExists = !Double.isNaN(toValue); - boolean byExists = !Double.isNaN(byValue); - - if (fromExists && toExists) - { - return (toValue - fromValue) * reps; - } - else if (fromExists && byExists) - { - return (fromValue + byValue) * reps; - } - else if (toExists && byExists) - { - return toValue * reps; - } - else if (byExists) - { - return byValue * reps; - } - - //Should not reach this line - return 0; - } - - @Override - protected void rebuild(AnimTimeParser animTimeParser) throws SVGException - { - super.rebuild(animTimeParser); - - StyleAttribute sty = new StyleAttribute(); - - if (getPres(sty.setName("from"))) - { - String strn = sty.getStringValue(); - if (XMLParseUtil.isDouble(strn)) - { - fromValue = XMLParseUtil.parseDouble(strn); - } - else - { - fromColor = ColorTable.parseColor(strn); - if (fromColor == null) - { - //Try path - fromPath = this.buildPath(strn, GeneralPath.WIND_EVEN_ODD); - dataType = DT_PATH; - } - else dataType = DT_COLOR; - } - } - - if (getPres(sty.setName("to"))) - { - String strn = sty.getStringValue(); - if (XMLParseUtil.isDouble(strn)) - { - toValue = XMLParseUtil.parseDouble(strn); - } - else - { - toColor = ColorTable.parseColor(strn); - if (toColor == null) - { - //Try path - toPath = this.buildPath(strn, GeneralPath.WIND_EVEN_ODD); - dataType = DT_PATH; - } - else dataType = DT_COLOR; - } - } - - if (getPres(sty.setName("by"))) - { - String strn = sty.getStringValue(); - if (strn != null) byValue = XMLParseUtil.parseDouble(strn); - } - - if (getPres(sty.setName("values"))) - { - String strn = sty.getStringValue(); - if (strn != null) valuesValue = XMLParseUtil.parseDoubleList(strn); - } - } - - /** - * @return the fromValue - */ - public double getFromValue() - { - return fromValue; - } - - /** - * @param fromValue the fromValue to set - */ - public void setFromValue(double fromValue) - { - this.fromValue = fromValue; - } - - /** - * @return the toValue - */ - public double getToValue() - { - return toValue; - } - - /** - * @param toValue the toValue to set - */ - public void setToValue(double toValue) - { - this.toValue = toValue; - } - - /** - * @return the byValue - */ - public double getByValue() - { - return byValue; - } - - /** - * @param byValue the byValue to set - */ - public void setByValue(double byValue) - { - this.byValue = byValue; - } - - /** - * @return the valuesValue - */ - public double[] getValuesValue() - { - return valuesValue; - } - - /** - * @param valuesValue the valuesValue to set - */ - public void setValuesValue(double[] valuesValue) - { - this.valuesValue = valuesValue; - } - - /** - * @return the fromColor - */ - public Color getFromColor() - { - return fromColor; - } - - /** - * @param fromColor the fromColor to set - */ - public void setFromColor(Color fromColor) - { - this.fromColor = fromColor; - } - - /** - * @return the toColor - */ - public Color getToColor() - { - return toColor; - } - - /** - * @param toColor the toColor to set - */ - public void setToColor(Color toColor) - { - this.toColor = toColor; - } - - /** - * @return the fromPath - */ - public GeneralPath getFromPath() - { - return fromPath; - } - - /** - * @param fromPath the fromPath to set - */ - public void setFromPath(GeneralPath fromPath) - { - this.fromPath = fromPath; - } - - /** - * @return the toPath - */ - public GeneralPath getToPath() - { - return toPath; - } - - /** - * @param toPath the toPath to set - */ - public void setToPath(GeneralPath toPath) - { - this.toPath = toPath; - } - -} --- a/src/com/kitfox/svg/animation/AnimateBase.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on August 15, 2004, 2:51 AM - */ - -package com.kitfox.svg.animation; - -import com.kitfox.svg.SVGConst; -import com.kitfox.svg.SVGElement; -import com.kitfox.svg.SVGException; -import com.kitfox.svg.SVGLoaderHelper; -import com.kitfox.svg.animation.parser.AnimTimeParser; -import com.kitfox.svg.animation.parser.ParseException; -import com.kitfox.svg.xml.StyleAttribute; -import java.io.StringReader; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.xml.sax.Attributes; -import org.xml.sax.SAXException; - -/** - * @author Mark McKay - * @author Mark McKay - */ -abstract public class AnimateBase extends AnimationElement -{ - private double repeatCount = Double.NaN; - private TimeBase repeatDur; - - /** Creates a new instance of Animate */ - public AnimateBase() - { - } - - @Override - public void evalParametric(AnimationTimeEval state, double curTime) - { - evalParametric(state, curTime, repeatCount, repeatDur == null ? Double.NaN : repeatDur.evalTime()); - } - - @Override - public void loaderStartElement(SVGLoaderHelper helper, Attributes attrs, SVGElement parent) throws SAXException - { - //Load style string - super.loaderStartElement(helper, attrs, parent); - - String repeatDurTime = attrs.getValue("repeatDur"); - - try - { - if (repeatDurTime != null) - { - helper.animTimeParser.ReInit(new StringReader(repeatDurTime)); - this.repeatDur = helper.animTimeParser.Expr(); - this.repeatDur.setParentElement(this); - } - } - catch (Exception e) - { - throw new SAXException(e); - } - - String strn = attrs.getValue("repeatCount"); - if (strn == null) - { - repeatCount = 1; - } - else if ("indefinite".equals(strn)) - { - repeatCount = Double.POSITIVE_INFINITY; - } - else - { - try { repeatCount = Double.parseDouble(strn); } - catch (Exception e) { repeatCount = Double.NaN; } - } - } - - @Override - protected void rebuild(AnimTimeParser animTimeParser) throws SVGException - { - super.rebuild(animTimeParser); - - StyleAttribute sty = new StyleAttribute(); - - if (getPres(sty.setName("repeatDur"))) - { - String strn = sty.getStringValue(); - if (strn != null) - { - animTimeParser.ReInit(new StringReader(strn)); - try - { - this.repeatDur = animTimeParser.Expr(); - } - catch (ParseException ex) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, - "Could not parse '" + strn + "'", ex); - } - } - } - - if (getPres(sty.setName("repeatCount"))) - { - String strn = sty.getStringValue(); - if (strn == null) - { - repeatCount = 1; - } - else if ("indefinite".equals(strn)) - { - repeatCount = Double.POSITIVE_INFINITY; - } - else - { - try { repeatCount = Double.parseDouble(strn); } - catch (Exception e) { repeatCount = Double.NaN; } - } - } - } - - /** - * @return the repeatCount - */ - public double getRepeatCount() - { - return repeatCount; - } - - /** - * @param repeatCount the repeatCount to set - */ - public void setRepeatCount(double repeatCount) - { - this.repeatCount = repeatCount; - } - - /** - * @return the repeatDur - */ - public TimeBase getRepeatDur() - { - return repeatDur; - } - - /** - * @param repeatDur the repeatDur to set - */ - public void setRepeatDur(TimeBase repeatDur) - { - this.repeatDur = repeatDur; - } -} --- a/src/com/kitfox/svg/animation/AnimateColor.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on August 15, 2004, 2:51 AM - */ - -package com.kitfox.svg.animation; - -import com.kitfox.svg.SVGElement; -import com.kitfox.svg.SVGException; -import com.kitfox.svg.SVGLoaderHelper; -import com.kitfox.svg.animation.parser.AnimTimeParser; -import com.kitfox.svg.xml.ColorTable; -import com.kitfox.svg.xml.StyleAttribute; -import java.awt.Color; -import org.xml.sax.Attributes; -import org.xml.sax.SAXException; - - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class AnimateColor extends AnimateBase implements AnimateColorIface -{ - public static final String TAG_NAME = "animateColor"; - - - private Color fromValue; - private Color toValue; - - /** Creates a new instance of Animate */ - public AnimateColor() - { - } - - @Override - public String getTagName() - { - return TAG_NAME; - } - - @Override - public void loaderStartElement(SVGLoaderHelper helper, Attributes attrs, SVGElement parent) throws SAXException - { - //Load style string - super.loaderStartElement(helper, attrs, parent); - - String strn = attrs.getValue("from"); - fromValue = ColorTable.parseColor(strn); - - strn = attrs.getValue("to"); - toValue = ColorTable.parseColor(strn); - } - - - /** - * Evaluates this animation element for the passed interpolation time. Interp - * must be on [0..1]. - */ - public Color evalColor(double interp) - { - int r1 = fromValue.getRed(); - int g1 = fromValue.getGreen(); - int b1 = fromValue.getBlue(); - int r2 = toValue.getRed(); - int g2 = toValue.getGreen(); - int b2 = toValue.getBlue(); - double invInterp = 1.0 - interp; - - return new Color((int)(r1 * invInterp + r2 * interp), - (int)(g1 * invInterp + g2 * interp), - (int)(b1 * invInterp + b2 * interp)); - } - - @Override - protected void rebuild(AnimTimeParser animTimeParser) throws SVGException - { - super.rebuild(animTimeParser); - - StyleAttribute sty = new StyleAttribute(); - - if (getPres(sty.setName("from"))) - { - String strn = sty.getStringValue(); - fromValue = ColorTable.parseColor(strn); - } - - if (getPres(sty.setName("to"))) - { - String strn = sty.getStringValue(); - toValue = ColorTable.parseColor(strn); - } - } - - /** - * @return the fromValue - */ - public Color getFromValue() - { - return fromValue; - } - - /** - * @param fromValue the fromValue to set - */ - public void setFromValue(Color fromValue) - { - this.fromValue = fromValue; - } - - /** - * @return the toValue - */ - public Color getToValue() - { - return toValue; - } - - /** - * @param toValue the toValue to set - */ - public void setToValue(Color toValue) - { - this.toValue = toValue; - } -} --- a/src/com/kitfox/svg/animation/AnimateColorIface.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on January 16, 2005, 6:24 AM - */ - -package com.kitfox.svg.animation; - -import java.awt.*; - -/** - * - * @author kitfox - */ -public interface AnimateColorIface -{ - public Color evalColor(double interp); -} --- a/src/com/kitfox/svg/animation/AnimateMotion.java +++ /dev/null @@ -1,347 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on August 15, 2004, 2:51 AM - */ - -package com.kitfox.svg.animation; - -import com.kitfox.svg.SVGElement; -import com.kitfox.svg.SVGException; -import com.kitfox.svg.SVGLoaderHelper; -import com.kitfox.svg.animation.parser.AnimTimeParser; -import com.kitfox.svg.xml.StyleAttribute; -import java.awt.geom.AffineTransform; -import java.awt.geom.GeneralPath; -import java.awt.geom.PathIterator; -import java.awt.geom.Point2D; -import java.util.ArrayList; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import org.xml.sax.Attributes; -import org.xml.sax.SAXException; - - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class AnimateMotion extends AnimateXform -{ - public static final String TAG_NAME = "animateMotion"; - - static final Pattern patPoint = Pattern.compile("\\s*(\\d+)[^\\d]+(\\d+)\\s*"); - -// protected double fromValue; -// protected double toValue; - private GeneralPath path; - private int rotateType = RT_ANGLE; - private double rotate; //Static angle to rotate by - - public static final int RT_ANGLE = 0; //Rotate by constant 'rotate' degrees - public static final int RT_AUTO = 1; //Rotate to reflect tangent of position on path - - final ArrayList bezierSegs = new ArrayList(); - double curveLength; - - /** Creates a new instance of Animate */ - public AnimateMotion() - { - } - - @Override - public String getTagName() - { - return TAG_NAME; - } - - @Override - public void loaderStartElement(SVGLoaderHelper helper, Attributes attrs, SVGElement parent) throws SAXException - { - //Load style string - super.loaderStartElement(helper, attrs, parent); - - //Motion element implies animating the transform element - if (attribName == null) - { - attribName = "transform"; - attribType = AT_AUTO; - setAdditiveType(AD_SUM); - } - - - String path = attrs.getValue("path"); - if (path != null) - { - this.path = buildPath(path, GeneralPath.WIND_NON_ZERO); - } - - //Now parse rotation style - String rotate = attrs.getValue("rotate"); - if (rotate != null) - { - if (rotate.equals("auto")) - { - this.rotateType = RT_AUTO; - } - else - { - try { this.rotate = Math.toRadians(Float.parseFloat(rotate)); } catch (Exception e) {} - } - } - - //Determine path - String from = attrs.getValue("from"); - String to = attrs.getValue("to"); - - buildPath(from, to); - } - - protected static void setPoint(Point2D.Float pt, String x, String y) - { - try { pt.x = Float.parseFloat(x); } catch (Exception e) {}; - - try { pt.y = Float.parseFloat(y); } catch (Exception e) {}; - } - - private void buildPath(String from, String to) - { - if (from != null && to != null) - { - Point2D.Float ptFrom = new Point2D.Float(), ptTo = new Point2D.Float(); - - Matcher matchPoint = patPoint.matcher(from); - if (matchPoint.matches()) - { - setPoint(ptFrom, matchPoint.group(1), matchPoint.group(2)); - } - - matchPoint.reset(to); - if (matchPoint.matches()) - { - setPoint(ptFrom, matchPoint.group(1), matchPoint.group(2)); - } - - if (ptFrom != null && ptTo != null) - { - path = new GeneralPath(); - path.moveTo(ptFrom.x, ptFrom.y); - path.lineTo(ptTo.x, ptTo.y); - } - } - - paramaterizePath(); - } - - private void paramaterizePath() - { - bezierSegs.clear(); - curveLength = 0; - - double[] coords = new double[6]; - double sx = 0, sy = 0; - - for (PathIterator pathIt = path.getPathIterator(new AffineTransform()); !pathIt.isDone(); pathIt.next()) - { - Bezier bezier = null; - - int segType = pathIt.currentSegment(coords); - - switch (segType) - { - case PathIterator.SEG_LINETO: - { - bezier = new Bezier(sx, sy, coords, 1); - sx = coords[0]; - sy = coords[1]; - break; - } - case PathIterator.SEG_QUADTO: - { - bezier = new Bezier(sx, sy, coords, 2); - sx = coords[2]; - sy = coords[3]; - break; - } - case PathIterator.SEG_CUBICTO: - { - bezier = new Bezier(sx, sy, coords, 3); - sx = coords[4]; - sy = coords[5]; - break; - } - case PathIterator.SEG_MOVETO: - { - sx = coords[0]; - sy = coords[1]; - break; - } - case PathIterator.SEG_CLOSE: - //Do nothing - break; - - } - - if (bezier != null) - { - bezierSegs.add(bezier); - curveLength += bezier.getLength(); - } - } - } - - /** - * Evaluates this animation element for the passed interpolation time. Interp - * must be on [0..1]. - */ - @Override - public AffineTransform eval(AffineTransform xform, double interp) - { - Point2D.Double point = new Point2D.Double(); - - if (interp >= 1) - { - Bezier last = (Bezier)bezierSegs.get(bezierSegs.size() - 1); - last.getFinalPoint(point); - xform.setToTranslation(point.x, point.y); - return xform; - } - - double curLength = curveLength * interp; - for (Bezier bez : bezierSegs) { - double bezLength = bez.getLength(); - if (curLength < bezLength) - { - double param = curLength / bezLength; - bez.eval(param, point); - break; - } - - curLength -= bezLength; - } - - xform.setToTranslation(point.x, point.y); - - return xform; - } - - - @Override - protected void rebuild(AnimTimeParser animTimeParser) throws SVGException - { - super.rebuild(animTimeParser); - - StyleAttribute sty = new StyleAttribute(); - - if (getPres(sty.setName("path"))) - { - String strn = sty.getStringValue(); - this.path = buildPath(strn, GeneralPath.WIND_NON_ZERO); - } - - if (getPres(sty.setName("rotate"))) - { - String strn = sty.getStringValue(); - if (strn.equals("auto")) - { - this.rotateType = RT_AUTO; - } - else - { - try { this.rotate = Math.toRadians(Float.parseFloat(strn)); } catch (Exception e) {} - } - } - - String from = null; - if (getPres(sty.setName("from"))) - { - from = sty.getStringValue(); - } - - String to = null; - if (getPres(sty.setName("to"))) - { - to = sty.getStringValue(); - } - - buildPath(from, to); - } - - /** - * @return the path - */ - public GeneralPath getPath() - { - return path; - } - - /** - * @param path the path to set - */ - public void setPath(GeneralPath path) - { - this.path = path; - } - - /** - * @return the rotateType - */ - public int getRotateType() - { - return rotateType; - } - - /** - * @param rotateType the rotateType to set - */ - public void setRotateType(int rotateType) - { - this.rotateType = rotateType; - } - - /** - * @return the rotate - */ - public double getRotate() - { - return rotate; - } - - /** - * @param rotate the rotate to set - */ - public void setRotate(double rotate) - { - this.rotate = rotate; - } -} --- a/src/com/kitfox/svg/animation/AnimateTransform.java +++ /dev/null @@ -1,398 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on August 15, 2004, 2:51 AM - */ - -package com.kitfox.svg.animation; - -import com.kitfox.svg.SVGElement; -import com.kitfox.svg.SVGException; -import com.kitfox.svg.SVGLoaderHelper; -import com.kitfox.svg.animation.parser.AnimTimeParser; -import com.kitfox.svg.xml.StyleAttribute; -import com.kitfox.svg.xml.XMLParseUtil; -import java.awt.geom.AffineTransform; -import java.util.regex.Pattern; -import org.xml.sax.Attributes; -import org.xml.sax.SAXException; - - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class AnimateTransform extends AnimateXform -{ - public static final String TAG_NAME = "animateTransform"; - -// protected AffineTransform fromValue; -// protected AffineTransform toValue; -// protected double[] fromValue; //Transform parameters -// protected double[] toValue; - private double[][] values; - private double[] keyTimes; - - public static final int AT_REPLACE = 0; - public static final int AT_SUM = 1; - - private int additive = AT_REPLACE; - - public static final int TR_TRANSLATE = 0; - public static final int TR_ROTATE = 1; - public static final int TR_SCALE = 2; - public static final int TR_SKEWY = 3; - public static final int TR_SKEWX = 4; - public static final int TR_INVALID = 5; - - private int xformType = TR_INVALID; - - /** Creates a new instance of Animate */ - public AnimateTransform() - { - } - - @Override - public String getTagName() - { - return TAG_NAME; - } - - @Override - public void loaderStartElement(SVGLoaderHelper helper, Attributes attrs, SVGElement parent) throws SAXException - { - //Load style string - super.loaderStartElement(helper, attrs, parent); - - //Type of matrix of transform. Should be one of the known names used to - // define matrix transforms - // valid types: translate, scale, rotate, skewX, skewY - // 'matrix' not valid for animation - String type = attrs.getValue("type").toLowerCase(); - if (type.equals("translate")) xformType = TR_TRANSLATE; - if (type.equals("rotate")) xformType = TR_ROTATE; - if (type.equals("scale")) xformType = TR_SCALE; - if (type.equals("skewx")) xformType = TR_SKEWX; - if (type.equals("skewy")) xformType = TR_SKEWY; - - String fromStrn = attrs.getValue("from"); - String toStrn = attrs.getValue("to"); - if (fromStrn != null && toStrn != null) - { - //fromValue = parseSingleTransform(type + "(" + strn + ")"); - double[] fromValue = XMLParseUtil.parseDoubleList(fromStrn); - fromValue = validate(fromValue); - - // toValue = parseSingleTransform(type + "(" + strn + ")"); - double[] toValue = XMLParseUtil.parseDoubleList(toStrn); - toValue = validate(toValue); - - values = new double[][]{fromValue, toValue}; - keyTimes = new double[]{0, 1}; - } - - String keyTimeStrn = attrs.getValue("keyTimes"); - String valuesStrn = attrs.getValue("values"); - if (keyTimeStrn != null && valuesStrn != null) - { - keyTimes = XMLParseUtil.parseDoubleList(keyTimeStrn); - - String[] valueList = Pattern.compile(";").split(valuesStrn); - values = new double[valueList.length][]; - for (int i = 0; i < valueList.length; i++) - { - double[] list = XMLParseUtil.parseDoubleList(valueList[i]); - values[i] = validate(list); - } - } - - //Check our additive state - String additive = attrs.getValue("additive"); - if (additive != null) - { - if (additive.equals("sum")) this.additive = AT_SUM; - } - } - - /** - * Check list size against current xform type and ensure list - * is expanded to a standard list size - */ - private double[] validate(double[] paramList) - { - switch (xformType) - { - case TR_SCALE: - { - if (paramList == null) - { - paramList = new double[]{1, 1}; - } - else if (paramList.length == 1) - { - paramList = new double[]{paramList[0], paramList[0]}; - -// double[] tmp = paramList; -// paramList = new double[2]; -// paramList[0] = paramList[1] = tmp[0]; - } - } - } - - return paramList; - } - - /** - * Evaluates this animation element for the passed interpolation time. Interp - * must be on [0..1]. - */ - @Override - public AffineTransform eval(AffineTransform xform, double interp) - { - int idx = 0; - for (; idx < keyTimes.length - 1; idx++) - { - if (interp >= keyTimes[idx]) - { - idx--; - if (idx < 0) idx = 0; - break; - } - } - - double spanStartTime = keyTimes[idx]; - double spanEndTime = keyTimes[idx + 1]; -// double span = spanStartTime - spanEndTime; - - interp = (interp - spanStartTime) / (spanEndTime - spanStartTime); - double[] fromValue = values[idx]; - double[] toValue = values[idx + 1]; - - switch (xformType) - { - case TR_TRANSLATE: - { - double x0 = fromValue.length >= 1 ? fromValue[0] : 0; - double x1 = toValue.length >= 1 ? toValue[0] : 0; - double y0 = fromValue.length >= 2 ? fromValue[1] : 0; - double y1 = toValue.length >= 2 ? toValue[1] : 0; - - double x = lerp(x0, x1, interp); - double y = lerp(y0, y1, interp); - - xform.setToTranslation(x, y); - break; - } - case TR_ROTATE: - { - double x1 = fromValue.length == 3 ? fromValue[1] : 0; - double y1 = fromValue.length == 3 ? fromValue[2] : 0; - double x2 = toValue.length == 3 ? toValue[1] : 0; - double y2 = toValue.length == 3 ? toValue[2] : 0; - - double theta = lerp(fromValue[0], toValue[0], interp); - double x = lerp(x1, x2, interp); - double y = lerp(y1, y2, interp); - xform.setToRotation(Math.toRadians(theta), x, y); - break; - } - case TR_SCALE: - { - double x0 = fromValue.length >= 1 ? fromValue[0] : 1; - double x1 = toValue.length >= 1 ? toValue[0] : 1; - double y0 = fromValue.length >= 2 ? fromValue[1] : 1; - double y1 = toValue.length >= 2 ? toValue[1] : 1; - - double x = lerp(x0, x1, interp); - double y = lerp(y0, y1, interp); - xform.setToScale(x, y); - break; - } - case TR_SKEWX: - { - double x = lerp(fromValue[0], toValue[0], interp); - xform.setToShear(Math.toRadians(x), 0.0); - break; - } - case TR_SKEWY: - { - double y = lerp(fromValue[0], toValue[0], interp); - xform.setToShear(0.0, Math.toRadians(y)); - break; - } - default: - xform.setToIdentity(); - break; - } - - return xform; - } - - @Override - protected void rebuild(AnimTimeParser animTimeParser) throws SVGException - { - super.rebuild(animTimeParser); - - StyleAttribute sty = new StyleAttribute(); - - if (getPres(sty.setName("type"))) - { - String strn = sty.getStringValue().toLowerCase(); - if (strn.equals("translate")) xformType = TR_TRANSLATE; - if (strn.equals("rotate")) xformType = TR_ROTATE; - if (strn.equals("scale")) xformType = TR_SCALE; - if (strn.equals("skewx")) xformType = TR_SKEWX; - if (strn.equals("skewy")) xformType = TR_SKEWY; - } - - String fromStrn = null; - if (getPres(sty.setName("from"))) - { - fromStrn = sty.getStringValue(); - } - - String toStrn = null; - if (getPres(sty.setName("to"))) - { - toStrn = sty.getStringValue(); - } - - if (fromStrn != null && toStrn != null) - { - double[] fromValue = XMLParseUtil.parseDoubleList(fromStrn); - fromValue = validate(fromValue); - - double[] toValue = XMLParseUtil.parseDoubleList(toStrn); - toValue = validate(toValue); - - values = new double[][]{fromValue, toValue}; - } - - String keyTimeStrn = null; - if (getPres(sty.setName("keyTimes"))) - { - keyTimeStrn = sty.getStringValue(); - } - - String valuesStrn = null; - if (getPres(sty.setName("values"))) - { - valuesStrn = sty.getStringValue(); - } - - if (keyTimeStrn != null && valuesStrn != null) - { - keyTimes = XMLParseUtil.parseDoubleList(keyTimeStrn); - - String[] valueList = Pattern.compile(";").split(valuesStrn); - values = new double[valueList.length][]; - for (int i = 0; i < valueList.length; i++) - { - double[] list = XMLParseUtil.parseDoubleList(valueList[i]); - values[i] = validate(list); - } - } - - //Check our additive state - - if (getPres(sty.setName("additive"))) - { - String strn = sty.getStringValue().toLowerCase(); - if (strn.equals("sum")) this.additive = AT_SUM; - } - } - - /** - * @return the values - */ - public double[][] getValues() - { - return values; - } - - /** - * @param values the values to set - */ - public void setValues(double[][] values) - { - this.values = values; - } - - /** - * @return the keyTimes - */ - public double[] getKeyTimes() - { - return keyTimes; - } - - /** - * @param keyTimes the keyTimes to set - */ - public void setKeyTimes(double[] keyTimes) - { - this.keyTimes = keyTimes; - } - - /** - * @return the additive - */ - public int getAdditive() - { - return additive; - } - - /** - * @param additive the additive to set - */ - public void setAdditive(int additive) - { - this.additive = additive; - } - - /** - * @return the xformType - */ - public int getXformType() - { - return xformType; - } - - /** - * @param xformType the xformType to set - */ - public void setXformType(int xformType) - { - this.xformType = xformType; - } -} --- a/src/com/kitfox/svg/animation/AnimateXform.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on January 14, 2005, 6:46 AM - */ - -package com.kitfox.svg.animation; - -import com.kitfox.svg.SVGElement; -import com.kitfox.svg.SVGLoaderHelper; -import java.awt.geom.AffineTransform; -import org.xml.sax.Attributes; -import org.xml.sax.SAXException; - - - -/** - * - * @author kitfox - */ -abstract public class AnimateXform extends AnimateBase -{ - public AnimateXform() - { - } - - @Override - public void loaderStartElement(SVGLoaderHelper helper, Attributes attrs, SVGElement parent) throws SAXException - { - super.loaderStartElement(helper, attrs, parent); - } - - abstract public AffineTransform eval(AffineTransform xform, double interp); - -} --- a/src/com/kitfox/svg/animation/AnimationElement.java +++ /dev/null @@ -1,512 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on August 15, 2004, 2:52 AM - */ - -package com.kitfox.svg.animation; - -import com.kitfox.svg.SVGConst; -import com.kitfox.svg.SVGElement; -import com.kitfox.svg.SVGException; -import com.kitfox.svg.SVGLoaderHelper; -import com.kitfox.svg.animation.parser.AnimTimeParser; -import com.kitfox.svg.animation.parser.ParseException; -import com.kitfox.svg.xml.StyleAttribute; -import java.io.StringReader; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.xml.sax.Attributes; -import org.xml.sax.SAXException; - - -/** - * @author Mark McKay - * @author Mark McKay - */ -public abstract class AnimationElement extends SVGElement -{ - protected String attribName; -// protected String attribType; - protected int attribType = AT_AUTO; - - public static final int AT_CSS = 0; - public static final int AT_XML = 1; - public static final int AT_AUTO = 2; //Check CSS first, then XML - - private TimeBase beginTime; - private TimeBase durTime; - private TimeBase endTime; - private int fillType = FT_AUTO; - - /** More about the fill attribute */ - public static final int FT_REMOVE = 0; - public static final int FT_FREEZE = 1; - public static final int FT_HOLD = 2; - public static final int FT_TRANSITION = 3; - public static final int FT_AUTO = 4; - public static final int FT_DEFAULT = 5; - - /** Additive state of track */ - public static final int AD_REPLACE = 0; - public static final int AD_SUM = 1; - - private int additiveType = AD_REPLACE; - - /** Accumlative state */ - public static final int AC_REPLACE = 0; - public static final int AC_SUM = 1; - - private int accumulateType = AC_REPLACE; - - /** Creates a new instance of AnimateEle */ - public AnimationElement() - { - } - - public static String animationElementToString(int attrValue) - { - switch (attrValue) - { - case AT_CSS: - return "CSS"; - case AT_XML: - return "XML"; - case AT_AUTO: - return "AUTO"; - default: - throw new RuntimeException("Unknown element type"); - } - } - - @Override - public void loaderStartElement(SVGLoaderHelper helper, Attributes attrs, SVGElement parent) throws SAXException - { - //Load style string - super.loaderStartElement(helper, attrs, parent); - - attribName = attrs.getValue("attributeName"); - String attribType = attrs.getValue("attributeType"); - if (attribType != null) - { - attribType = attribType.toLowerCase(); - if (attribType.equals("css")) this.attribType = AT_CSS; - else if (attribType.equals("xml")) this.attribType = AT_XML; - } - - String beginTime = attrs.getValue("begin"); - String durTime = attrs.getValue("dur"); - String endTime = attrs.getValue("end"); - - try - { - if (beginTime != null) - { - helper.animTimeParser.ReInit(new StringReader(beginTime)); - this.beginTime = helper.animTimeParser.Expr(); - this.beginTime.setParentElement(this); - } - - if (durTime != null) - { - helper.animTimeParser.ReInit(new StringReader(durTime)); - this.durTime = helper.animTimeParser.Expr(); - this.durTime.setParentElement(this); - } - - if (endTime != null) - { - helper.animTimeParser.ReInit(new StringReader(endTime)); - this.endTime = helper.animTimeParser.Expr(); - this.endTime.setParentElement(this); - } - } - catch (Exception e) - { - throw new SAXException(e); - } - -// this.beginTime = TimeBase.parseTime(beginTime); -// this.durTime = TimeBase.parseTime(durTime); -// this.endTime = TimeBase.parseTime(endTime); - - String fill = attrs.getValue("fill"); - - if (fill != null) - { - if (fill.equals("remove")) this.fillType = FT_REMOVE; - if (fill.equals("freeze")) this.fillType = FT_FREEZE; - if (fill.equals("hold")) this.fillType = FT_HOLD; - if (fill.equals("transiton")) this.fillType = FT_TRANSITION; - if (fill.equals("auto")) this.fillType = FT_AUTO; - if (fill.equals("default")) this.fillType = FT_DEFAULT; - } - - String additiveStrn = attrs.getValue("additive"); - - if (additiveStrn != null) - { - if (additiveStrn.equals("replace")) this.additiveType = AD_REPLACE; - if (additiveStrn.equals("sum")) this.additiveType = AD_SUM; - } - - String accumulateStrn = attrs.getValue("accumulate"); - - if (accumulateStrn != null) - { - if (accumulateStrn.equals("replace")) this.accumulateType = AC_REPLACE; - if (accumulateStrn.equals("sum")) this.accumulateType = AC_SUM; - } - } - - public String getAttribName() { return attribName; } - public int getAttribType() { return attribType; } - public int getAdditiveType() { return additiveType; } - public int getAccumulateType() { return accumulateType; } - - public void evalParametric(AnimationTimeEval state, double curTime) - { - evalParametric(state, curTime, Double.NaN, Double.NaN); - } - - /** - * Compares current time to start and end times and determines what degree - * of time interpolation this track currently represents. Returns - * Float.NaN if this track cannot be evaluated at the passed time (ie, - * it is before or past the end of the track, or it depends upon - * an unknown event) - * @param state - A structure that will be filled with information - * regarding the applicability of this animatoin element at the passed - * time. - * @param curTime - Current time in seconds - * @param repeatCount - Optional number of repetitions of length 'dur' to - * do. Set to Double.NaN to not consider this in the calculation. - * @param repeatDur - Optional amoun tof time to repeat the animaiton. - * Set to Double.NaN to not consider this in the calculation. - */ - protected void evalParametric(AnimationTimeEval state, double curTime, double repeatCount, double repeatDur) - { - double begin = (beginTime == null) ? 0 : beginTime.evalTime(); - if (Double.isNaN(begin) || begin > curTime) - { - state.set(Double.NaN, 0); - return; - } - - double dur = (durTime == null) ? Double.NaN : durTime.evalTime(); - if (Double.isNaN(dur)) - { - state.set(Double.NaN, 0); - return; - } - - //Determine end point of this animation - double end = (endTime == null) ? Double.NaN : endTime.evalTime(); - double repeat; -// if (Double.isNaN(repeatDur)) -// { -// repeatDur = dur; -// } - if (Double.isNaN(repeatCount) && Double.isNaN(repeatDur)) - { - repeat = Double.NaN; - } - else - { - repeat = Math.min( - Double.isNaN(repeatCount) ? Double.POSITIVE_INFINITY : dur * repeatCount, - Double.isNaN(repeatDur) ? Double.POSITIVE_INFINITY : repeatDur); - } - if (Double.isNaN(repeat) && Double.isNaN(end)) - { - //If neither and end point nor a repeat is specified, end point is - // implied by duration. - end = begin + dur; - } - - double finishTime; - if (Double.isNaN(end)) - { - finishTime = begin + repeat; - } - else if (Double.isNaN(repeat)) - { - finishTime = end; - } - else - { - finishTime = Math.min(end, repeat); - } - - double evalTime = Math.min(curTime, finishTime); -// if (curTime > finishTime) evalTime = finishTime; - - -// double evalTime = curTime; - -// boolean pastEnd = curTime > evalTime; - -// if (!Double.isNaN(end) && curTime > end) { pastEnd = true; evalTime = Math.min(evalTime, end); } -// if (!Double.isNaN(repeat) && curTime > repeat) { pastEnd = true; evalTime = Math.min(evalTime, repeat); } - - double ratio = (evalTime - begin) / dur; - int rep = (int)ratio; - double interp = ratio - rep; - - //Adjust for roundoff - if (interp < 0.00001) interp = 0; - -// state.set(interp, rep); -// if (!pastEnd) -// { -// state.set(interp, rep, false); -// return; -// } - - //If we are still within the clip, return value - if (curTime == evalTime) - { - state.set(interp, rep); - return; - } - - //We are past end of clip. Determine to clamp or ignore. - switch (fillType) - { - default: - case FT_REMOVE: - case FT_AUTO: - case FT_DEFAULT: - state.set(Double.NaN, rep); - return; - case FT_FREEZE: - case FT_HOLD: - case FT_TRANSITION: - state.set(interp == 0 ? 1 : interp, rep); - return; - } - - } - - double evalStartTime() - { - return beginTime == null ? Double.NaN : beginTime.evalTime(); - } - - double evalDurTime() - { - return durTime == null ? Double.NaN : durTime.evalTime(); - } - - /** - * Evaluates the ending time of this element. Returns 0 if not specified. - * - * @see hasEndTime - */ - double evalEndTime() - { - return endTime == null ? Double.NaN : endTime.evalTime(); - } - - /** - * Checks to see if an end time has been specified for this element. - */ - boolean hasEndTime() { return endTime != null; } - - /** - * Updates all attributes in this diagram associated with a time event. - * Ie, all attributes with track information. - * @return - true if this node has changed state as a result of the time - * update - */ - @Override - public boolean updateTime(double curTime) - { - //Animation elements to not change with time - return false; - } - - public void rebuild() throws SVGException - { - AnimTimeParser animTimeParser = new AnimTimeParser(new StringReader("")); - - rebuild(animTimeParser); - } - - protected void rebuild(AnimTimeParser animTimeParser) throws SVGException - { - StyleAttribute sty = new StyleAttribute(); - - if (getPres(sty.setName("begin"))) - { - String newVal = sty.getStringValue(); - animTimeParser.ReInit(new StringReader(newVal)); - try { - this.beginTime = animTimeParser.Expr(); - } catch (ParseException ex) { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, - "Could not parse '" + newVal + "'", ex); - } - } - - if (getPres(sty.setName("dur"))) - { - String newVal = sty.getStringValue(); - animTimeParser.ReInit(new StringReader(newVal)); - try { - this.durTime = animTimeParser.Expr(); - } catch (ParseException ex) { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, - "Could not parse '" + newVal + "'", ex); - } - } - - if (getPres(sty.setName("end"))) - { - String newVal = sty.getStringValue(); - animTimeParser.ReInit(new StringReader(newVal)); - try { - this.endTime = animTimeParser.Expr(); - } catch (ParseException ex) { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, - "Could not parse '" + newVal + "'", ex); - } - } - - if (getPres(sty.setName("fill"))) - { - String newVal = sty.getStringValue(); - if (newVal.equals("remove")) this.fillType = FT_REMOVE; - if (newVal.equals("freeze")) this.fillType = FT_FREEZE; - if (newVal.equals("hold")) this.fillType = FT_HOLD; - if (newVal.equals("transiton")) this.fillType = FT_TRANSITION; - if (newVal.equals("auto")) this.fillType = FT_AUTO; - if (newVal.equals("default")) this.fillType = FT_DEFAULT; - } - - if (getPres(sty.setName("additive"))) - { - String newVal = sty.getStringValue(); - if (newVal.equals("replace")) this.additiveType = AD_REPLACE; - if (newVal.equals("sum")) this.additiveType = AD_SUM; - } - - if (getPres(sty.setName("accumulate"))) - { - String newVal = sty.getStringValue(); - if (newVal.equals("replace")) this.accumulateType = AC_REPLACE; - if (newVal.equals("sum")) this.accumulateType = AC_SUM; - } - - } - - /** - * @return the beginTime - */ - public TimeBase getBeginTime() - { - return beginTime; - } - - /** - * @param beginTime the beginTime to set - */ - public void setBeginTime(TimeBase beginTime) - { - this.beginTime = beginTime; - } - - /** - * @return the durTime - */ - public TimeBase getDurTime() - { - return durTime; - } - - /** - * @param durTime the durTime to set - */ - public void setDurTime(TimeBase durTime) - { - this.durTime = durTime; - } - - /** - * @return the endTime - */ - public TimeBase getEndTime() - { - return endTime; - } - - /** - * @param endTime the endTime to set - */ - public void setEndTime(TimeBase endTime) - { - this.endTime = endTime; - } - - /** - * @return the fillType - */ - public int getFillType() - { - return fillType; - } - - /** - * @param fillType the fillType to set - */ - public void setFillType(int fillType) - { - this.fillType = fillType; - } - - /** - * @param additiveType the additiveType to set - */ - public void setAdditiveType(int additiveType) - { - this.additiveType = additiveType; - } - - /** - * @param accumulateType the accumulateType to set - */ - public void setAccumulateType(int accumulateType) - { - this.accumulateType = accumulateType; - } -} --- a/src/com/kitfox/svg/animation/AnimationTimeEval.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on September 21, 2004, 1:31 PM - */ - -package com.kitfox.svg.animation; - -/** - * - * @author kitfox - */ -public class AnimationTimeEval -{ - /** - * Value on [0..1] representing the interpolation value of queried animation - * element, or Double.NaN if element does not provide a valid evalutaion - */ - public double interp; - - /** - * Number of completed repetitions - */ - public int rep; - - /** - * True if this evaluation is in a frozen state; ie, past the end of the - * track and held in the "freeze" state. - */ -// public boolean pastEnd; - - /** Creates a new instance of AnimateTimeEval */ - public AnimationTimeEval() - { - } - -// public void set(double interp, int rep, boolean pastEnd) - public void set(double interp, int rep) - { - this.interp = interp; - this.rep = rep; -// this.pastEnd = pastEnd; - } -} --- a/src/com/kitfox/svg/animation/Bezier.java +++ /dev/null @@ -1,210 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on January 14, 2005, 4:08 AM - */ - -package com.kitfox.svg.animation; - -import java.awt.geom.*; - -/** - * http://mathworld.wolfram.com/BezierCurve.html - * @author kitfox - */ -public class Bezier -{ - double length; - double[] coord; - - public Bezier(double sx, double sy, double[] coords, int numCoords) - { - setCoords(sx, sy, coords, numCoords); - } - - public void setCoords(double sx, double sy, double[] coords, int numCoords) - { - coord = new double[numCoords * 2 + 2]; - coord[0] = sx; - coord[1] = sy; - for (int i = 0; i < numCoords; i++) - { - coord[i * 2 + 2] = coords[i * 2]; - coord[i * 2 + 3] = coords[i * 2 + 1]; - } - - calcLength(); - } - - /** - * Retuns aproximation of the length of the bezier - */ - public double getLength() - { - return length; - } - - private void calcLength() - { - length = 0; - for (int i = 2; i < coord.length; i += 2) - { - length += lineLength(coord[i - 2], coord[i - 1], coord[i], coord[i + 1]); - } - } - - private double lineLength(double x1, double y1, double x2, double y2) - { - double dx = x2 - x1, dy = y2 - y1; - return Math.sqrt(dx * dx + dy * dy); - } - - public Point2D.Double getFinalPoint(Point2D.Double point) - { - point.x = coord[coord.length - 2]; - point.y = coord[coord.length - 1]; - return point; - } - - public Point2D.Double eval(double param, Point2D.Double point) - { - point.x = 0; - point.y = 0; - int numKnots = coord.length / 2; - - for (int i = 0; i < numKnots; i++) - { - double scale = bernstein(numKnots - 1, i, param); - point.x += coord[i * 2] * scale; - point.y += coord[i * 2 + 1] * scale; - } - - return point; - } - - /** - * Calculates the bernstein polynomial for evaluating parametric bezier - * @param numKnots - one less than number of knots in this curve hull - * @param knotNo - knot we are evaluating Bernstein for - * @param param - Parametric value we are evaluating at - */ - private double bernstein(int numKnots, int knotNo, double param) - { - double iParam = 1 - param; - //Faster evaluation for easy cases: - switch (numKnots) - { - case 0: - return 1; - case 1: - { - switch (knotNo) - { - case 0: - return iParam; - case 1: - return param; - } - break; - } - case 2: - { - switch (knotNo) - { - case 0: - return iParam * iParam; - case 1: - return 2 * iParam * param; - case 2: - return param * param; - } - break; - } - case 3: - { - switch (knotNo) - { - case 0: - return iParam * iParam * iParam; - case 1: - return 3 * iParam * iParam * param; - case 2: - return 3 * iParam * param * param; - case 3: - return param * param * param; - } - break; - } - } - - //If this bezier has more than four points, calculate bernstein the hard way - double retVal = 1; - for (int i = 0; i < knotNo; i++) - { - retVal *= param; - } - for (int i = 0; i < numKnots - knotNo; i++) - { - retVal *= iParam; - } - retVal *= choose(numKnots, knotNo); - - return retVal; - } - - - - private int choose(int num, int denom) - { - int denom2 = num - denom; - if (denom < denom2) - { - int tmp = denom; - denom = denom2; - denom2 = tmp; - } - - int prod = 1; - for (int i = num; i > denom; i--) - { - prod *= num; - } - - for (int i = 2; i <= denom2; i++) - { - prod /= i; - } - - return prod; - } -} --- a/src/com/kitfox/svg/animation/SetSmil.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on August 15, 2004, 2:51 AM - */ - -package com.kitfox.svg.animation; - -import com.kitfox.svg.SVGElement; -import com.kitfox.svg.SVGException; -import com.kitfox.svg.SVGLoaderHelper; -import com.kitfox.svg.animation.parser.AnimTimeParser; -import com.kitfox.svg.xml.StyleAttribute; -import org.xml.sax.Attributes; -import org.xml.sax.SAXException; - - -/** - * Set is used to set a textual value; most likely for a style element. - * - * @author Mark McKay - * @author Mark McKay - */ -public class SetSmil extends AnimationElement -{ - public static final String TAG_NAME = "set"; - - private String toValue; - - /** Creates a new instance of Set */ - public SetSmil() - { - } - - @Override - public String getTagName() - { - return TAG_NAME; - } - - @Override - public void loaderStartElement(SVGLoaderHelper helper, Attributes attrs, SVGElement parent) throws SAXException - { - //Load style string - super.loaderStartElement(helper, attrs, parent); - - toValue = attrs.getValue("to"); - } - - @Override - protected void rebuild(AnimTimeParser animTimeParser) throws SVGException - { - super.rebuild(animTimeParser); - - StyleAttribute sty = new StyleAttribute(); - - if (getPres(sty.setName("to"))) - { - String newVal = sty.getStringValue(); - toValue = newVal; - } - } - - /** - * @return the toValue - */ - public String getToValue() - { - return toValue; - } - - /** - * @param toValue the toValue to set - */ - public void setToValue(String toValue) - { - this.toValue = toValue; - } -} --- a/src/com/kitfox/svg/animation/TimeBase.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on August 15, 2004, 3:31 AM - */ - -package com.kitfox.svg.animation; - -import java.util.regex.*; - -/** - * SVG has a complicated way of specifying time. Potentially, a time could - * be represened as a summation of discrete times and times of other animation - * events. This provides a root for the many elements we will need to define - * time. - * - * @author Mark McKay - * @author Mark McKay - */ -abstract public class TimeBase -{ - static final Pattern patIndefinite = Pattern.compile("\\s*indefinite\\s*"); - static final Pattern patUnitTime = Pattern.compile("\\s*([-+]?((\\d*\\.\\d+)|(\\d+))([-+]?[eE]\\d+)?)\\s*(h|min|s|ms)?\\s*"); - - /* - public static TimeBase parseTime(String text) - { - if (text == null) return null; - - if (text.indexOf('+') == -1) - { - return parseTimeComponent(text); - } - - return new TimeCompound(text); - } - */ - - protected static TimeBase parseTimeComponent(String text) - { - Matcher matchIndefinite = patIndefinite.matcher(text); - if (matchIndefinite.matches()) return new TimeIndefinite(); - - Matcher matchUnitTime = patUnitTime.matcher(text); - if (matchUnitTime.matches()) - { - String val = matchUnitTime.group(1); - String units = matchUnitTime.group(6); - - double time = 0; - try { time = Double.parseDouble(val); } - catch (Exception e) {} - - if (units.equals("ms")) time *= .001; - else if (units.equals("min")) time *= 60; - else if (units.equals("h")) time *= 3600; - - return new TimeDiscrete(time); - } - - return null; - } - - /** - * Calculates the (greater than or equal to 0) time in seconds this - * time represents. If the time cannot be determined, returns - * Double.NaN. If this represents an infinte amount of time, returns - * Double.POSITIVE_INFINITY. - */ - abstract public double evalTime(); - - /** - * Some time elements need to refer to the animation element that contains - * them to evaluate correctly - */ - public void setParentElement(AnimationElement ele) - { - } -} --- a/src/com/kitfox/svg/animation/TimeCompound.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on August 15, 2004, 3:33 AM - */ - -package com.kitfox.svg.animation; - -import java.util.Collections; -import java.util.List; -import java.util.regex.Pattern; - - -/** - * This represents a summation of other time elements. It is used for complex - * timing events with offsets. - * - * @author Mark McKay - * @author Mark McKay - */ -public class TimeCompound extends TimeBase -{ - static final Pattern patPlus = Pattern.compile("\\+"); - - /** - * This is a list of times. This element's time is calculated as the greatest - * member that is less than the current time. - */ - final List componentTimes; - - private AnimationElement parent; - - /** Creates a new instance of TimeDiscrete */ - public TimeCompound(List timeBases) - { - componentTimes = Collections.unmodifiableList(timeBases); - } - - @Override - public double evalTime() - { - double agg = 0.0; - - for (TimeBase timeEle : componentTimes) { - double time = timeEle.evalTime(); - agg += time; - } - - return agg; - } - - @Override - public void setParentElement(AnimationElement ele) - { - this.parent = ele; - - for (TimeBase timeEle : componentTimes) { - timeEle.setParentElement(ele); - } - } -} --- a/src/com/kitfox/svg/animation/TimeDiscrete.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on August 15, 2004, 3:33 AM - */ - -package com.kitfox.svg.animation; - -/** - * This is a time that represents a specific number of milliseconds - * - * @author Mark McKay - * @author Mark McKay - */ -public class TimeDiscrete extends TimeBase -{ - //Milliseconds of delay - double secs; - - /** Creates a new instance of TimeDiscrete */ - public TimeDiscrete(double secs) - { - this.secs = secs; - } - - @Override - public double evalTime() - { - return secs; - } - -} --- a/src/com/kitfox/svg/animation/TimeIndefinite.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on August 15, 2004, 3:33 AM - */ - -package com.kitfox.svg.animation; - -/** - * This represents the indefinite (infinite) amount of time. - * - * @author Mark McKay - * @author Mark McKay - */ -public class TimeIndefinite extends TimeBase -{ - - /** Creates a new instance of TimeDiscrete */ - public TimeIndefinite() - { - } - - @Override - public double evalTime() - { - return Double.POSITIVE_INFINITY; - } - -} --- a/src/com/kitfox/svg/animation/TimeLookup.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on August 15, 2004, 3:33 AM - */ - -package com.kitfox.svg.animation; - -/** - * This is a time that represents a specific number of milliseconds - * - * @author Mark McKay - * @author Mark McKay - */ -public class TimeLookup extends TimeBase -{ - /** - * This time can only be resolved in relation to it's parent - */ - private AnimationElement parent; - - /** - * Node this lookup acts upon - */ - String node; - - /** - * Event to evalutae on this node - */ - String event; - - /** - * Optional parameter used by some events - */ - String paramList; - - /** Creates a new instance of TimeDiscrete */ - public TimeLookup(AnimationElement parent, String node, String event, String paramList) - { - this.parent = parent; - this.node = node; - this.event = event; - this.paramList = paramList; - } - - @Override - public double evalTime() - { - return 0.0; - } - - @Override - public void setParentElement(AnimationElement ele) - { - parent = ele; - } -} --- a/src/com/kitfox/svg/animation/TimeSum.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on August 15, 2004, 3:33 AM - */ - -package com.kitfox.svg.animation; - -/** - * This is a time that represents a specific number of milliseconds - * - * @author Mark McKay - * @author Mark McKay - */ -public class TimeSum extends TimeBase -{ - //Milliseconds of delay - TimeBase t1; - TimeBase t2; - boolean add; - - /** Creates a new instance of TimeDiscrete */ - public TimeSum(TimeBase t1, TimeBase t2, boolean add) - { - this.t1 = t1; - this.t2 = t2; - this.add = add; - } - - @Override - public double evalTime() - { - return add ? t1.evalTime() + t2.evalTime() : t1.evalTime() - t2.evalTime(); - } - - @Override - public void setParentElement(AnimationElement ele) - { - t1.setParentElement(ele); - t2.setParentElement(ele); - } -} --- a/src/com/kitfox/svg/animation/TrackBase.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on August 15, 2004, 11:34 PM - */ - -package com.kitfox.svg.animation; - -import java.util.*; - -import com.kitfox.svg.xml.*; -import com.kitfox.svg.*; - -/** - * A track holds the animation events for a single parameter of a single SVG - * element. It also contains the default value for the element, should the - * user want to see the 'unanimated' value. - * - * @author Mark McKay - * @author Mark McKay - */ -abstract public class TrackBase -{ - protected final String attribName; - protected final int attribType; //AnimationElement.AT_* - - /** Element we're animating */ - protected final SVGElement parent; - - //It doesn't make sense to sort this, since some events will depend on - // other events - in many cases, there will be no meaningful sorted order. - final ArrayList animEvents = new ArrayList(); - - /** Creates a new instance of TrackManager */ -// public TrackBase(SVGElement parent) -// { -// this(parent, "", AnimationElement.AT_AUTO); -// } - - /** - * Creates a track that would be valid for the name and type of element - * passed in. Does not actually add this elemnt to the track. - */ - public TrackBase(SVGElement parent, AnimationElement ele) throws SVGElementException - { - this(parent, ele.getAttribName(), ele.getAttribType()); - } - - public TrackBase(SVGElement parent, String attribName, int attribType) throws SVGElementException - { - this.parent = parent; - this.attribName = attribName; - this.attribType = attribType; - - //Make sure parent has an attribute we will write to - if (attribType == AnimationElement.AT_AUTO - && !parent.hasAttribute(attribName, AnimationElement.AT_CSS) - && !parent.hasAttribute(attribName, AnimationElement.AT_XML)) - { - parent.addAttribute(attribName, AnimationElement.AT_CSS, ""); - } - else if (!parent.hasAttribute(attribName, attribType)) - { - parent.addAttribute(attribName, attribType, ""); - } - } - - public String getAttribName() { return attribName; } - public int getAttribType() { return attribType; } - - public void addElement(AnimationElement ele) - { - animEvents.add(ele); - } - - /** - * Returns a StyleAttribute representing the value of this track at the - * passed time. If this track does not apply, returns null. - * @return - True if successful, false if a value could not be obtained - */ - abstract public boolean getValue(StyleAttribute attrib, double curTime) throws SVGException; - -} --- a/src/com/kitfox/svg/animation/TrackColor.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on September 21, 2004, 11:34 PM - */ - -package com.kitfox.svg.animation; - -import com.kitfox.svg.xml.StyleAttribute; -import java.awt.*; -import java.util.*; - -import com.kitfox.svg.*; - -/** - * A track holds the animation events for a single parameter of a single SVG - * element. It also contains the default value for the element, should the - * user want to see the 'unanimated' value. - * - * @author Mark McKay - * @author Mark McKay - */ -public class TrackColor extends TrackBase -{ - - public TrackColor(AnimationElement ele) throws SVGElementException - { - super(ele.getParent(), ele); - } - - @Override - public boolean getValue(StyleAttribute attrib, double curTime) - { - Color col = getValue(curTime); - if (col == null) return false; - - attrib.setStringValue("#" + Integer.toHexString(col.getRGB())); - return true; - } - - public Color getValue(double curTime) - { - Color retVal = null; - AnimationTimeEval state = new AnimationTimeEval(); - - for (AnimationElement animationElement : animEvents) { - AnimateBase ele = (AnimateBase)animationElement; - AnimateColorIface eleColor = (AnimateColorIface)ele; - ele.evalParametric(state, curTime); - - //Reject value if it is in the invalid state - if (Double.isNaN(state.interp)) continue; - - if (retVal == null) - { - retVal = eleColor.evalColor(state.interp); - continue; - } - - Color curCol = eleColor.evalColor(state.interp); - switch (ele.getAdditiveType()) - { - case AnimationElement.AD_REPLACE: - retVal = curCol; - break; - case AnimationElement.AD_SUM: - retVal = new Color(curCol.getRed() + retVal.getRed(), curCol.getGreen() + retVal.getGreen(), curCol.getBlue() + retVal.getBlue()); - break; - } - } - - return retVal; - } -} --- a/src/com/kitfox/svg/animation/TrackDouble.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on August 15, 2004, 11:34 PM - */ - -package com.kitfox.svg.animation; - -import com.kitfox.svg.xml.StyleAttribute; -import java.util.*; - -import com.kitfox.svg.*; - -/** - * A track holds the animation events for a single parameter of a single SVG - * element. It also contains the default value for the element, should the - * user want to see the 'unanimated' value. - * - * @author Mark McKay - * @author Mark McKay - */ -public class TrackDouble extends TrackBase -{ - public TrackDouble(AnimationElement ele) throws SVGElementException - { - super(ele.getParent(), ele); - } - - @Override - public boolean getValue(StyleAttribute attrib, double curTime) - { - double val = getValue(curTime); - if (Double.isNaN(val)) return false; - - attrib.setStringValue("" + val); - return true; - } - - public double getValue(double curTime) - { - double retVal = Double.NaN; - - StyleAttribute attr = null; - switch (attribType) - { - case AnimationElement.AT_CSS: - attr = parent.getStyleAbsolute(attribName); - retVal = attr.getDoubleValue(); - break; - case AnimationElement.AT_XML: - attr = parent.getPresAbsolute(attribName); - retVal = attr.getDoubleValue(); - break; - case AnimationElement.AT_AUTO: - attr = parent.getStyleAbsolute(attribName); - if (attr == null) attr = parent.getPresAbsolute(attribName); - retVal = attr.getDoubleValue(); - break; - } - - - - AnimationTimeEval state = new AnimationTimeEval(); -// boolean pastEnd = true; - - for (AnimationElement animationElement : animEvents) { - Animate ele = (Animate)animationElement; - ele.evalParametric(state, curTime); - - //Go to next element if this one does not affect processing - if (Double.isNaN(state.interp)) continue; - - switch (ele.getAdditiveType()) - { - case AnimationElement.AD_SUM: - retVal += ele.eval(state.interp); - break; - case AnimationElement.AD_REPLACE: - retVal = ele.eval(state.interp); - break; - } - - //Evalutae accumulation if applicable - if (state.rep > 0) - { - switch (ele.getAccumulateType()) - { - case AnimationElement.AC_SUM: - retVal += ele.repeatSkipSize(state.rep); - break; - } - - } - } - - return retVal; - } -} --- a/src/com/kitfox/svg/animation/TrackManager.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on August 15, 2004, 11:34 PM - */ - -package com.kitfox.svg.animation; - -import java.util.*; - -import com.kitfox.svg.*; - -import java.io.Serializable; - -/** - * Every element contains tracks, which manage the animation. There is one track - * for every parameter with animation, and each track in turn is composed of - * many events. - * - * @author Mark McKay - * @author Mark McKay - */ -public class TrackManager implements Serializable -{ - public static final long serialVersionUID = 0; - - static class TrackKey - { - String name; - int type; - - TrackKey(AnimationElement base) - { - this(base.getAttribName(), base.getAttribType()); - } - - TrackKey(String name, int type) - { - this.name = name; - this.type = type; - } - - @Override - public int hashCode() - { - int hash = name == null ? 0 : name.hashCode(); - hash = hash * 97 + type; - return hash; - } - - @Override - public boolean equals(Object obj) - { - if (!(obj instanceof TrackKey)) return false; - TrackKey key = (TrackKey)obj; - return key.type == type && key.name.equals(name); - } - } - - HashMap tracks = new HashMap(); - - /** Creates a new instance of TrackManager */ - public TrackManager() - { - } - - /** - * Adds a new animation element to this track - */ - public void addTrackElement(AnimationElement element) throws SVGElementException - { - TrackKey key = new TrackKey(element); - - TrackBase track = (TrackBase)tracks.get(key); - - if (track == null) - { - //Create a track for this element - if (element instanceof Animate) - { - switch (((Animate)element).getDataType()) - { - case Animate.DT_REAL: - track = new TrackDouble(element); - break; - case Animate.DT_COLOR: - track = new TrackColor(element); - break; - case Animate.DT_PATH: - track = new TrackPath(element); - break; - default: - throw new RuntimeException(""); - } - } - else if (element instanceof AnimateColor) - { - track = new TrackColor(element); - } - else if (element instanceof AnimateTransform || element instanceof AnimateMotion) - { - track = new TrackTransform(element); - } - - tracks.put(key, track); - } - - track.addElement(element); - } - - public TrackBase getTrack(String name, int type) - { - //Handle AUTO, which will match either CSS or XML (in that order) - if (type == AnimationElement.AT_AUTO) - { - TrackBase t = getTrack(name, AnimationElement.AT_CSS); - if (t != null) return t; - t = getTrack(name, AnimationElement.AT_XML); - if (t != null) return t; - return null; - } - - //Get requested attribute - TrackKey key = new TrackKey(name, type); - TrackBase t = (TrackBase)tracks.get(key); - if (t != null) return t; - - //If that didn't exist, see if one exists of type AUTO - key = new TrackKey(name, AnimationElement.AT_AUTO); - return (TrackBase)tracks.get(key); - } - - public int getNumTracks() - { - return tracks.size(); - } - - public Iterator iterator() - { - return tracks.values().iterator(); - } -} --- a/src/com/kitfox/svg/animation/TrackMotion.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on September 21, 2004, 11:34 PM - */ - -package com.kitfox.svg.animation; - -import com.kitfox.svg.xml.StyleAttribute; -import java.awt.geom.*; -import java.util.*; - -import com.kitfox.svg.*; - -/** - * A track holds the animation events for a single parameter of a single SVG - * element. It also contains the default value for the element, should the - * user want to see the 'unanimated' value. - * - * @author Mark McKay - * @author Mark McKay - */ -public class TrackMotion extends TrackBase -{ - public TrackMotion(AnimationElement ele) throws SVGElementException - { - //The motion element implies a CSS attribute of transform -// super(ele.getParent(), "transform", AnimationElement.AT_CSS); - super(ele.getParent(), ele); - } - - @Override - public boolean getValue(StyleAttribute attrib, double curTime) throws SVGException - { - AffineTransform retVal = new AffineTransform(); - retVal = getValue(retVal, curTime); -// AffineTransform val = getValue(curTime); -// if (val == null) return false; - - double[] mat = new double[6]; - retVal.getMatrix(mat); - attrib.setStringValue("matrix(" + mat[0] + " " + mat[1] + " " + mat[2] + " " + mat[3] + " " + mat[4] + " " + mat[5] + ")"); - return true; - } - - public AffineTransform getValue(AffineTransform retVal, double curTime) throws SVGException - { - //Init transform with default state - StyleAttribute attr = null; - switch (attribType) - { - case AnimationElement.AT_CSS: - attr = parent.getStyleAbsolute(attribName); - retVal.setTransform(SVGElement.parseSingleTransform(attr.getStringValue())); - break; - case AnimationElement.AT_XML: - attr = parent.getPresAbsolute(attribName); - retVal.setTransform(SVGElement.parseSingleTransform(attr.getStringValue())); - break; - case AnimationElement.AT_AUTO: - attr = parent.getStyleAbsolute(attribName); - if (attr == null) attr = parent.getPresAbsolute(attribName); - retVal.setTransform(SVGElement.parseSingleTransform(attr.getStringValue())); - break; - } - - - //Update transform with time based information - AnimationTimeEval state = new AnimationTimeEval(); - AffineTransform xform = new AffineTransform(); -// boolean pastEnd = true; - - for (AnimationElement animationElement : animEvents) { - AnimateMotion ele = (AnimateMotion)animationElement; - ele.evalParametric(state, curTime); - - //Go to next element if this one does not affect processing - if (Double.isNaN(state.interp)) continue; - - switch (ele.getAdditiveType()) - { - case AnimationElement.AD_SUM: - retVal.concatenate(ele.eval(xform, state.interp)); - break; - case AnimationElement.AD_REPLACE: - retVal.setTransform(ele.eval(xform, state.interp)); - break; - } - - //Evaluate accumulation if applicable -/* - if (state.rep > 0) - { - switch (ele.getAccumulateType()) - { - case AnimationElement.AC_SUM: - retVal += ele.repeatSkipSize(state.rep); - break; - } - - } -*/ - } - - return retVal; - } -} --- a/src/com/kitfox/svg/animation/TrackPath.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on September 21, 2004, 11:34 PM - */ - -package com.kitfox.svg.animation; - -import com.kitfox.svg.xml.StyleAttribute; -import java.awt.geom.*; -import java.util.*; - -import com.kitfox.svg.pathcmd.*; -import com.kitfox.svg.*; - -/** - * A track holds the animation events for a single parameter of a single SVG - * element. It also contains the default value for the element, should the - * user want to see the 'unanimated' value. - * - * @author Mark McKay - * @author Mark McKay - */ -public class TrackPath extends TrackBase -{ - - public TrackPath(AnimationElement ele) throws SVGElementException - { - super(ele.getParent(), ele); - } - - @Override - public boolean getValue(StyleAttribute attrib, double curTime) - { - GeneralPath path = getValue(curTime); - if (path == null) return false; - - attrib.setStringValue(PathUtil.buildPathString(path)); - return true; - } - - public GeneralPath getValue(double curTime) - { - GeneralPath retVal = null; - AnimationTimeEval state = new AnimationTimeEval(); - - for (AnimationElement animationElement : animEvents) { - AnimateBase ele = (AnimateBase)animationElement; - Animate eleAnim = (Animate)ele; - ele.evalParametric(state, curTime); - - //Reject value if it is in the invalid state - if (Double.isNaN(state.interp)) continue; - - if (retVal == null) - { - retVal = eleAnim.evalPath(state.interp); - continue; - } - - GeneralPath curPath = eleAnim.evalPath(state.interp); - switch (ele.getAdditiveType()) - { - case AnimationElement.AD_REPLACE: - retVal = curPath; - break; - case AnimationElement.AD_SUM: - throw new RuntimeException("Not implemented"); -// retVal = new Color(curCol.getRed() + retVal.getRed(), curCol.getGreen() + retVal.getGreen(), curCol.getBlue() + retVal.getBlue()); -// break; - default: - throw new RuntimeException(); - } - } - - return retVal; - } -} --- a/src/com/kitfox/svg/animation/TrackTransform.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on September 21, 2004, 11:34 PM - */ - -package com.kitfox.svg.animation; - -import com.kitfox.svg.xml.StyleAttribute; -import java.awt.geom.*; -import java.util.*; - -import com.kitfox.svg.*; - -/** - * A track holds the animation events for a single parameter of a single SVG - * element. It also contains the default value for the element, should the - * user want to see the 'unanimated' value. - * - * @author Mark McKay - * @author Mark McKay - */ -public class TrackTransform extends TrackBase -{ - public TrackTransform(AnimationElement ele) throws SVGElementException - { - super(ele.getParent(), ele); - } - - @Override - public boolean getValue(StyleAttribute attrib, double curTime) throws SVGException - { - AffineTransform retVal = new AffineTransform(); - retVal = getValue(retVal, curTime); -// AffineTransform val = getValue(curTime); -// if (val == null) return false; - - double[] mat = new double[6]; - retVal.getMatrix(mat); - attrib.setStringValue("matrix(" + mat[0] + " " + mat[1] + " " + mat[2] + " " + mat[3] + " " + mat[4] + " " + mat[5] + ")"); - return true; - } - - public AffineTransform getValue(AffineTransform retVal, double curTime) throws SVGException - { - //Init transform with default state - StyleAttribute attr = null; - switch (attribType) - { - case AnimationElement.AT_CSS: - attr = parent.getStyleAbsolute(attribName); - retVal.setTransform(SVGElement.parseSingleTransform(attr.getStringValue())); - break; - case AnimationElement.AT_XML: - attr = parent.getPresAbsolute(attribName); - retVal.setTransform(SVGElement.parseSingleTransform(attr.getStringValue())); - break; - case AnimationElement.AT_AUTO: - attr = parent.getStyleAbsolute(attribName); - if (attr == null) attr = parent.getPresAbsolute(attribName); - retVal.setTransform(SVGElement.parseSingleTransform(attr.getStringValue())); - break; - } - - - //Update transform with time based information - AnimationTimeEval state = new AnimationTimeEval(); - AffineTransform xform = new AffineTransform(); - - for (AnimationElement animationElement : animEvents) { - AnimateXform ele = (AnimateXform)animationElement; - ele.evalParametric(state, curTime); - - //Go to next element if this one does not affect processing - if (Double.isNaN(state.interp)) continue; - - switch (ele.getAdditiveType()) - { - case AnimationElement.AD_SUM: - retVal.concatenate(ele.eval(xform, state.interp)); - break; - case AnimationElement.AD_REPLACE: - retVal.setTransform(ele.eval(xform, state.interp)); - break; - } - - } - - return retVal; - } -} --- a/src/com/kitfox/svg/animation/parser/ASTEventTime.java +++ /dev/null @@ -1,16 +0,0 @@ -/* Generated by: JJTree: Do not edit this line. ASTEventTime.java Version 1.1 */ -/* ParserGeneratorCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=false,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ -package com.kitfox.svg.animation.parser; - -public -class ASTEventTime extends SimpleNode { - public ASTEventTime(int id) { - super(id); - } - - public ASTEventTime(AnimTimeParser p, int id) { - super(p, id); - } - -} -/* ParserGeneratorCC - OriginalChecksum=9f82621b38ac3a11fee348d9c42565ac (do not edit this line) */ --- a/src/com/kitfox/svg/animation/parser/ASTExpr.java +++ /dev/null @@ -1,16 +0,0 @@ -/* Generated by: JJTree: Do not edit this line. ASTExpr.java Version 1.1 */ -/* ParserGeneratorCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=false,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ -package com.kitfox.svg.animation.parser; - -public -class ASTExpr extends SimpleNode { - public ASTExpr(int id) { - super(id); - } - - public ASTExpr(AnimTimeParser p, int id) { - super(p, id); - } - -} -/* ParserGeneratorCC - OriginalChecksum=a5a6c15738e716d7c2fcfdd1582e1348 (do not edit this line) */ --- a/src/com/kitfox/svg/animation/parser/ASTIndefiniteTime.java +++ /dev/null @@ -1,16 +0,0 @@ -/* Generated by: JJTree: Do not edit this line. ASTIndefiniteTime.java Version 1.1 */ -/* ParserGeneratorCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=false,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ -package com.kitfox.svg.animation.parser; - -public -class ASTIndefiniteTime extends SimpleNode { - public ASTIndefiniteTime(int id) { - super(id); - } - - public ASTIndefiniteTime(AnimTimeParser p, int id) { - super(p, id); - } - -} -/* ParserGeneratorCC - OriginalChecksum=5b7432790a26c4f1f28664667dd7625e (do not edit this line) */ --- a/src/com/kitfox/svg/animation/parser/ASTInteger.java +++ /dev/null @@ -1,16 +0,0 @@ -/* Generated by: JJTree: Do not edit this line. ASTInteger.java Version 1.1 */ -/* ParserGeneratorCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=false,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ -package com.kitfox.svg.animation.parser; - -public -class ASTInteger extends SimpleNode { - public ASTInteger(int id) { - super(id); - } - - public ASTInteger(AnimTimeParser p, int id) { - super(p, id); - } - -} -/* ParserGeneratorCC - OriginalChecksum=c944f38b296a70e8f4889dbeb12b84e2 (do not edit this line) */ --- a/src/com/kitfox/svg/animation/parser/ASTLiteralTime.java +++ /dev/null @@ -1,16 +0,0 @@ -/* Generated by: JJTree: Do not edit this line. ASTLiteralTime.java Version 1.1 */ -/* ParserGeneratorCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=false,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ -package com.kitfox.svg.animation.parser; - -public -class ASTLiteralTime extends SimpleNode { - public ASTLiteralTime(int id) { - super(id); - } - - public ASTLiteralTime(AnimTimeParser p, int id) { - super(p, id); - } - -} -/* ParserGeneratorCC - OriginalChecksum=bbc9b534f817272531fcf32065671dc5 (do not edit this line) */ --- a/src/com/kitfox/svg/animation/parser/ASTLookupTime.java +++ /dev/null @@ -1,16 +0,0 @@ -/* Generated by: JJTree: Do not edit this line. ASTLookupTime.java Version 1.1 */ -/* ParserGeneratorCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=false,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ -package com.kitfox.svg.animation.parser; - -public -class ASTLookupTime extends SimpleNode { - public ASTLookupTime(int id) { - super(id); - } - - public ASTLookupTime(AnimTimeParser p, int id) { - super(p, id); - } - -} -/* ParserGeneratorCC - OriginalChecksum=e1572a68100b43cdde68300d5b65cfe3 (do not edit this line) */ --- a/src/com/kitfox/svg/animation/parser/ASTNumber.java +++ /dev/null @@ -1,16 +0,0 @@ -/* Generated by: JJTree: Do not edit this line. ASTNumber.java Version 1.1 */ -/* ParserGeneratorCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=false,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ -package com.kitfox.svg.animation.parser; - -public -class ASTNumber extends SimpleNode { - public ASTNumber(int id) { - super(id); - } - - public ASTNumber(AnimTimeParser p, int id) { - super(p, id); - } - -} -/* ParserGeneratorCC - OriginalChecksum=845d1db5e885bf9ef58e9c634215c378 (do not edit this line) */ --- a/src/com/kitfox/svg/animation/parser/ASTParamList.java +++ /dev/null @@ -1,16 +0,0 @@ -/* Generated by: JJTree: Do not edit this line. ASTParamList.java Version 1.1 */ -/* ParserGeneratorCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=false,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ -package com.kitfox.svg.animation.parser; - -public -class ASTParamList extends SimpleNode { - public ASTParamList(int id) { - super(id); - } - - public ASTParamList(AnimTimeParser p, int id) { - super(p, id); - } - -} -/* ParserGeneratorCC - OriginalChecksum=6a2e1518e954af5faa5e030732a3aae6 (do not edit this line) */ --- a/src/com/kitfox/svg/animation/parser/ASTSum.java +++ /dev/null @@ -1,16 +0,0 @@ -/* Generated by: JJTree: Do not edit this line. ASTSum.java Version 1.1 */ -/* ParserGeneratorCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=false,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ -package com.kitfox.svg.animation.parser; - -public -class ASTSum extends SimpleNode { - public ASTSum(int id) { - super(id); - } - - public ASTSum(AnimTimeParser p, int id) { - super(p, id); - } - -} -/* ParserGeneratorCC - OriginalChecksum=1d87d9fb63342ca2c5b9afe7c6b3783d (do not edit this line) */ --- a/src/com/kitfox/svg/animation/parser/ASTTerm.java +++ /dev/null @@ -1,16 +0,0 @@ -/* Generated by: JJTree: Do not edit this line. ASTTerm.java Version 1.1 */ -/* ParserGeneratorCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=false,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ -package com.kitfox.svg.animation.parser; - -public -class ASTTerm extends SimpleNode { - public ASTTerm(int id) { - super(id); - } - - public ASTTerm(AnimTimeParser p, int id) { - super(p, id); - } - -} -/* ParserGeneratorCC - OriginalChecksum=1ba3d64975750e7f691f5a4a4f5d10e2 (do not edit this line) */ --- a/src/com/kitfox/svg/animation/parser/AbstractCharStream.java +++ /dev/null @@ -1,429 +0,0 @@ -/* Generated by: ParserGeneratorCC: Do not edit this line. AbstractCharStream.java Version 1.1 */ -/* ParserGeneratorCCOptions:SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ -package com.kitfox.svg.animation.parser; - -/** - * An implementation of interface CharStream, where the stream is assumed to - * contain only ASCII characters (without unicode processing). - */ - -public -abstract class AbstractCharStream -implements CharStream -{ - public static final int DEFAULT_BUF_SIZE = 4096; - - static final int hexval(final char c) throws java.io.IOException { - switch(c) - { - case '0' : - return 0; - case '1' : - return 1; - case '2' : - return 2; - case '3' : - return 3; - case '4' : - return 4; - case '5' : - return 5; - case '6' : - return 6; - case '7' : - return 7; - case '8' : - return 8; - case '9' : - return 9; - case 'a' : - case 'A' : - return 10; - case 'b' : - case 'B' : - return 11; - case 'c' : - case 'C' : - return 12; - case 'd' : - case 'D' : - return 13; - case 'e' : - case 'E' : - return 14; - case 'f' : - case 'F' : - return 15; - } - - // Should never come here - throw new java.io.IOException("Invalid hex char '" + c + "' provided!"); - } - - /** Position in buffer. */ - protected int bufpos = -1; - protected int bufsize; - protected int available; - protected int tokenBegin; - protected int[] bufline; - protected int[] bufcolumn; - - protected int column = 0; - protected int line = 1; - - protected boolean prevCharIsCR = false; - protected boolean prevCharIsLF = false; - - protected char[] buffer; - protected int maxNextCharInd = 0; - protected int inBuf = 0; - private int tabSize = 1; - protected char[] nextCharBuf; - protected int nextCharInd = -1; - private boolean trackLineColumn = true; - - public void setTabSize(final int i) - { - tabSize = i; - } - - public int getTabSize() - { - return tabSize; - } - - protected void expandBuff(final boolean wrapAround) - { - final char[] newbuffer = new char[bufsize + 2048]; - final int newbufline[] = new int[bufsize + 2048]; - final int newbufcolumn[] = new int[bufsize + 2048]; - - try - { - if (wrapAround) - { - System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); - System.arraycopy(buffer, 0, newbuffer, bufsize - tokenBegin, bufpos); - buffer = newbuffer; - - System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); - System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos); - bufline = newbufline; - - System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); - System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos); - bufcolumn = newbufcolumn; - - bufpos += (bufsize - tokenBegin); - maxNextCharInd = bufpos; - } - else - { - System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); - buffer = newbuffer; - - System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); - bufline = newbufline; - - System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); - bufcolumn = newbufcolumn; - - bufpos -= tokenBegin; - maxNextCharInd = bufpos; - } - } - catch (final Exception ex) - { - throw new IllegalStateException(ex); - } - - bufsize += 2048; - available = bufsize; - tokenBegin = 0; - } - - protected abstract int streamRead(char[] buf, int offset, int len) throws java.io.IOException; - - protected abstract void streamClose() throws java.io.IOException; - - protected void fillBuff() throws java.io.IOException - { - if (maxNextCharInd == available) - { - if (available == bufsize) - { - if (tokenBegin > 2048) - { - bufpos = maxNextCharInd = 0; - available = tokenBegin; - } - else - if (tokenBegin < 0) - bufpos = maxNextCharInd = 0; - else - expandBuff(false); - } - else - if (available > tokenBegin) - available = bufsize; - else - if ((tokenBegin - available) < 2048) - expandBuff(true); - else - available = tokenBegin; - } - - try { - final int i = streamRead(buffer, maxNextCharInd, available - maxNextCharInd); - if (i == -1) - { - streamClose(); - throw new java.io.IOException(); - } - maxNextCharInd += i; - return; - } - catch (final java.io.IOException e) { - --bufpos; - backup(0); - if (tokenBegin == -1) - tokenBegin = bufpos; - throw e; - } - } - - public char beginToken() throws java.io.IOException - { - tokenBegin = -1; - char c = readChar(); - tokenBegin = bufpos; - - return c; - } - - protected void updateLineColumn(char c) - { - column++; - - if (prevCharIsLF) - { - prevCharIsLF = false; - column = 1; - line++; - } - else - if (prevCharIsCR) - { - prevCharIsCR = false; - if (c == '\n') - prevCharIsLF = true; - else - { - column = 1; - line++; - } - } - - switch (c) - { - case '\r' : - prevCharIsCR = true; - break; - case '\n' : - prevCharIsLF = true; - break; - case '\t' : - column--; - column += (tabSize - (column % tabSize)); - break; - default : - break; - } - - bufline[bufpos] = line; - bufcolumn[bufpos] = column; - } - - /** Read a character. */ - public char readChar() throws java.io.IOException - { - if (inBuf > 0) - { - --inBuf; - - if (++bufpos == bufsize) - bufpos = 0; - - return buffer[bufpos]; - } - - ++bufpos; - if (bufpos >= maxNextCharInd) - fillBuff(); - - char c = buffer[bufpos]; - - if (trackLineColumn) - updateLineColumn(c); - return c; - } - - public int getBeginColumn() { - return bufcolumn[tokenBegin]; - } - - public int getBeginLine() { - return bufline[tokenBegin]; - } - - public int getEndColumn() { - return bufcolumn[bufpos]; - } - - public int getEndLine() { - return bufline[bufpos]; - } - - public void backup(final int amount) { - inBuf += amount; - bufpos -= amount; - if (bufpos < 0) - bufpos += bufsize; - } - - /** Constructor. */ - public AbstractCharStream(final int startline, - final int startcolumn, - final int buffersize) - { - line = startline; - column = startcolumn - 1; - - bufsize = buffersize; - available = buffersize; - buffer = new char[buffersize]; - bufline = new int[buffersize]; - bufcolumn = new int[buffersize]; - nextCharBuf = new char[4096]; - } - - /** Reinitialise. */ - public void reInit(final int startline, - final int startcolumn, - final int buffersize) - { - line = startline; - column = startcolumn - 1; - if (buffer == null || buffersize != buffer.length) - { - bufsize = buffersize; - available = buffersize; - buffer = new char[buffersize]; - bufline = new int[buffersize]; - bufcolumn = new int[buffersize]; - nextCharBuf = new char[4096]; - } - prevCharIsCR = false; - prevCharIsLF = false; - maxNextCharInd = 0; - inBuf = 0; - tokenBegin = 0; - bufpos = -1; - nextCharInd = -1; - } - - public String getImage() - { - if (bufpos >= tokenBegin) { - // from tokenBegin to bufpos - return new String(buffer, tokenBegin, bufpos - tokenBegin + 1); - } - - // from tokenBegin to bufpos including wrap around - return new String(buffer, tokenBegin, bufsize - tokenBegin) + - new String(buffer, 0, bufpos + 1); - } - - public char[] getSuffix(int len) - { - char[] ret = new char[len]; - if ((bufpos + 1) >= len) - System.arraycopy(buffer, bufpos - len + 1, ret, 0, len); - else - { - System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0, len - bufpos - 1); - System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1); - } - return ret; - } - - public void done() - { - nextCharBuf = null; - buffer = null; - bufline = null; - bufcolumn = null; - } - - /** - * Method to adjust line and column numbers for the start of a token. - */ - public void adjustBeginLineColumn(final int nNewLine, final int newCol) - { - int start = tokenBegin; - int newLine = nNewLine; - int len; - - if (bufpos >= tokenBegin) - { - len = bufpos - tokenBegin + inBuf + 1; - } - else - { - len = bufsize - tokenBegin + bufpos + 1 + inBuf; - } - - int i = 0; - int j = 0; - int k = 0; - int nextColDiff = 0; - int columnDiff = 0; - - // TODO disassemble meaning and split up - while (i < len && bufline[j = start % bufsize] == bufline[k = ++start % bufsize]) - { - bufline[j] = newLine; - nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j]; - bufcolumn[j] = newCol + columnDiff; - columnDiff = nextColDiff; - i++; - } - - if (i < len) - { - bufline[j] = newLine++; - bufcolumn[j] = newCol + columnDiff; - - while (i++ < len) - { - // TODO disassemble meaning and split up - if (bufline[j = start % bufsize] != bufline[++start % bufsize]) - bufline[j] = newLine++; - else - bufline[j] = newLine; - } - } - - line = bufline[j]; - column = bufcolumn[j]; - } - - public void setTrackLineColumn(final boolean tlc) { - trackLineColumn = tlc; - } - - public boolean isTrackLineColumn() { - return trackLineColumn; - } -} -/* ParserGeneratorCC - OriginalChecksum=42c00e00033ffe0cb350fd3452b6fa32 (do not edit this line) */ --- a/src/com/kitfox/svg/animation/parser/AnimTimeParser.java +++ /dev/null @@ -1,1002 +0,0 @@ -/* AnimTimeParser.java */ -/* Generated by: JJTree&ParserGeneratorCC: Do not edit this line. AnimTimeParser.java */ -package com.kitfox.svg.animation.parser; - -import com.kitfox.svg.SVGConst; -import com.kitfox.svg.animation.TimeBase; -import com.kitfox.svg.animation.TimeCompound; -import com.kitfox.svg.animation.TimeDiscrete; -import com.kitfox.svg.animation.TimeIndefinite; -import com.kitfox.svg.animation.TimeLookup; -import com.kitfox.svg.animation.TimeSum; -import java.io.StringReader; -import java.util.ArrayList; -import java.util.logging.Level; -import java.util.logging.Logger; - -public class AnimTimeParser/*@bgen(jjtree)*/implements AnimTimeParserTreeConstants, AnimTimeParserConstants {/*@bgen(jjtree)*/ - protected JJTAnimTimeParserState jjtree = new JJTAnimTimeParserState();/** - * Test the parser - */ - public static void main(String args[]) throws ParseException - { -// AnimTimeParser parser = new AnimTimeParser(System.in); - StringReader reader; - - reader = new StringReader("1:30 + 5ms"); - AnimTimeParser parser = new AnimTimeParser(reader); - TimeBase tc; - - tc = parser.Expr(); - System.err.println("AnimTimeParser eval to " + tc.evalTime()); - - reader = new StringReader("19"); - parser.ReInit(reader); - tc = parser.Expr(); - System.err.println("AnimTimeParser eval to " + tc.evalTime()); - } - -/** - * Expression structure - */ - final public - -TimeBase Expr() throws ParseException {/*@bgen(jjtree) Expr */ - ASTExpr jjtn000 = new ASTExpr(JJTEXPR); - boolean jjtc000 = true; - jjtree.openNodeScope(jjtn000);TimeBase term; - ArrayList list = new ArrayList(); - try { - switch (jj_ntk == -1 ? jj_ntk_f() : jj_ntk) { - case INTEGER: - case FLOAT: - case INDEFINITE: - case MOUSE_OVER: - case WHEN_NOT_ACTIVE: - case IDENTIFIER:{ - term = Sum(); -list.add(term); - break; - } - default: - jj_la1[0] = jj_gen; - ; - } - label_1: - while (true) { - if (jj_2_1(2)) { - } else { - break label_1; - } - jj_consume_token(15); - term = Sum(); -list.add(term); - } - switch (jj_ntk == -1 ? jj_ntk_f() : jj_ntk) { - case 15:{ - jj_consume_token(15); - break; - } - default: - jj_la1[1] = jj_gen; - ; - } -jjtree.closeNodeScope(jjtn000, true); - jjtc000 = false; -switch (list.size()) - { - case 0: - {if ("" != null) return new TimeIndefinite();} - case 1: - {if ("" != null) return (TimeBase)list.get(0);} - default: - {if ("" != null) return new TimeCompound(list);} - } - } catch (Throwable jjte000) { -if (jjtc000) { - jjtree.clearNodeScope(jjtn000); - jjtc000 = false; - } else { - jjtree.popNode(); - } - if (jjte000 instanceof ParseException) { - throw (ParseException)jjte000; - } - if (jjte000 instanceof RuntimeException) { - throw (RuntimeException)jjte000; - } - throw (Error)jjte000; - } finally { -if (jjtc000) { - jjtree.closeNodeScope(jjtn000, true); - } - } - throw new IllegalStateException ("Missing return statement in function"); -} - - final public TimeBase Sum() throws ParseException {/*@bgen(jjtree) Sum */ - ASTSum jjtn000 = new ASTSum(JJTSUM); - boolean jjtc000 = true; - jjtree.openNodeScope(jjtn000);Token t = null; - TimeBase t1; - TimeBase t2 = null; - try { - t1 = Term(); - switch (jj_ntk == -1 ? jj_ntk_f() : jj_ntk) { - case 16: - case 17:{ - switch (jj_ntk == -1 ? jj_ntk_f() : jj_ntk) { - case 16:{ - t = jj_consume_token(16); - break; - } - case 17:{ - t = jj_consume_token(17); - break; - } - default: - jj_la1[2] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - t2 = Term(); - break; - } - default: - jj_la1[3] = jj_gen; - ; - } -jjtree.closeNodeScope(jjtn000, true); - jjtc000 = false; -if (t2 == null) {if ("" != null) return t1;} - - if (t.image.equals("-")) - { - {if ("" != null) return new TimeSum(t1, t2, false);} - } - else - { - {if ("" != null) return new TimeSum(t1, t2, true);} - } - } catch (Throwable jjte000) { -if (jjtc000) { - jjtree.clearNodeScope(jjtn000); - jjtc000 = false; - } else { - jjtree.popNode(); - } - if (jjte000 instanceof ParseException) { - throw (ParseException)jjte000; - } - if (jjte000 instanceof RuntimeException) { - throw (RuntimeException)jjte000; - } - throw (Error)jjte000; - } finally { -if (jjtc000) { - jjtree.closeNodeScope(jjtn000, true); - } - } - throw new IllegalStateException ("Missing return statement in function"); -} - - final public TimeBase Term() throws ParseException {/*@bgen(jjtree) Term */ - ASTTerm jjtn000 = new ASTTerm(JJTTERM); - boolean jjtc000 = true; - jjtree.openNodeScope(jjtn000);TimeBase base; - try { - switch (jj_ntk == -1 ? jj_ntk_f() : jj_ntk) { - case INDEFINITE:{ - base = IndefiniteTime(); -jjtree.closeNodeScope(jjtn000, true); - jjtc000 = false; -{if ("" != null) return base;} - break; - } - case INTEGER: - case FLOAT:{ - base = LiteralTime(); -jjtree.closeNodeScope(jjtn000, true); - jjtc000 = false; -{if ("" != null) return base;} - break; - } - case IDENTIFIER:{ - base = LookupTime(); -jjtree.closeNodeScope(jjtn000, true); - jjtc000 = false; -{if ("" != null) return base;} - break; - } - case MOUSE_OVER: - case WHEN_NOT_ACTIVE:{ - base = EventTime(); -jjtree.closeNodeScope(jjtn000, true); - jjtc000 = false; -{if ("" != null) return base;} - break; - } - default: - jj_la1[4] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - } catch (Throwable jjte000) { -if (jjtc000) { - jjtree.clearNodeScope(jjtn000); - jjtc000 = false; - } else { - jjtree.popNode(); - } - if (jjte000 instanceof ParseException) { - throw (ParseException)jjte000; - } - if (jjte000 instanceof RuntimeException) { - throw (RuntimeException)jjte000; - } - throw (Error)jjte000; - } finally { -if (jjtc000) { - jjtree.closeNodeScope(jjtn000, true); - } - } - throw new IllegalStateException ("Missing return statement in function"); -} - - final public TimeIndefinite IndefiniteTime() throws ParseException {/*@bgen(jjtree) IndefiniteTime */ - ASTIndefiniteTime jjtn000 = new ASTIndefiniteTime(JJTINDEFINITETIME); - boolean jjtc000 = true; - jjtree.openNodeScope(jjtn000); - try { - jj_consume_token(INDEFINITE); -jjtree.closeNodeScope(jjtn000, true); - jjtc000 = false; -{if ("" != null) return new TimeIndefinite();} - } finally { -if (jjtc000) { - jjtree.closeNodeScope(jjtn000, true); - } - } - throw new IllegalStateException ("Missing return statement in function"); -} - - final public TimeDiscrete EventTime() throws ParseException {/*@bgen(jjtree) EventTime */ - ASTEventTime jjtn000 = new ASTEventTime(JJTEVENTTIME); - boolean jjtc000 = true; - jjtree.openNodeScope(jjtn000); - try { - switch (jj_ntk == -1 ? jj_ntk_f() : jj_ntk) { - case MOUSE_OVER:{ - jj_consume_token(MOUSE_OVER); - break; - } - case WHEN_NOT_ACTIVE:{ - jj_consume_token(WHEN_NOT_ACTIVE); - break; - } - default: - jj_la1[5] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } -jjtree.closeNodeScope(jjtn000, true); - jjtc000 = false; -//For now, map all events to the zero time - {if ("" != null) return new TimeDiscrete(0);} - } finally { -if (jjtc000) { - jjtree.closeNodeScope(jjtn000, true); - } - } - throw new IllegalStateException ("Missing return statement in function"); -} - - final public TimeDiscrete LiteralTime() throws ParseException {/*@bgen(jjtree) LiteralTime */ - ASTLiteralTime jjtn000 = new ASTLiteralTime(JJTLITERALTIME); - boolean jjtc000 = true; - jjtree.openNodeScope(jjtn000);double t1, t2, t3 = Double.NaN, value; - Token t; - try { - t1 = Number(); -value = t1; - switch (jj_ntk == -1 ? jj_ntk_f() : jj_ntk) { - case UNITS: - case 18:{ - switch (jj_ntk == -1 ? jj_ntk_f() : jj_ntk) { - case 18:{ - jj_consume_token(18); - t2 = Number(); - switch (jj_ntk == -1 ? jj_ntk_f() : jj_ntk) { - case 18:{ - jj_consume_token(18); - t3 = Number(); - break; - } - default: - jj_la1[6] = jj_gen; - ; - } -//Return clock time format (convert to seconds) - if (Double.isNaN(t3)) - { - value = t1 * 60 + t2; - } - else - { - value = t1 * 3600 + t2 * 60 + t3; - } - break; - } - case UNITS:{ - t = jj_consume_token(UNITS); -//Return units format (convert to seconds) - if (t.image.equals("ms")) value = t1 / 1000; - if (t.image.equals("min")) value = t1 * 60; - if (t.image.equals("h")) value = t1 * 3600; - break; - } - default: - jj_la1[7] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - break; - } - default: - jj_la1[8] = jj_gen; - ; - } -jjtree.closeNodeScope(jjtn000, true); - jjtc000 = false; -{if ("" != null) return new TimeDiscrete(value);} - } catch (Throwable jjte000) { -if (jjtc000) { - jjtree.clearNodeScope(jjtn000); - jjtc000 = false; - } else { - jjtree.popNode(); - } - if (jjte000 instanceof ParseException) { - throw (ParseException)jjte000; - } - if (jjte000 instanceof RuntimeException) { - throw (RuntimeException)jjte000; - } - throw (Error)jjte000; - } finally { -if (jjtc000) { - jjtree.closeNodeScope(jjtn000, true); - } - } - throw new IllegalStateException ("Missing return statement in function"); -} - - final public TimeLookup LookupTime() throws ParseException {/*@bgen(jjtree) LookupTime */ - ASTLookupTime jjtn000 = new ASTLookupTime(JJTLOOKUPTIME); - boolean jjtc000 = true; - jjtree.openNodeScope(jjtn000);double paramNum = 0.0; - Token node, event; - try { - node = jj_consume_token(IDENTIFIER); - jj_consume_token(19); - event = jj_consume_token(IDENTIFIER); - switch (jj_ntk == -1 ? jj_ntk_f() : jj_ntk) { - case 20:{ - paramNum = ParamList(); - break; - } - default: - jj_la1[9] = jj_gen; - ; - } -jjtree.closeNodeScope(jjtn000, true); - jjtc000 = false; -{if ("" != null) return new TimeLookup(null, node.image, event.image, "" + paramNum);} - } catch (Throwable jjte000) { -if (jjtc000) { - jjtree.clearNodeScope(jjtn000); - jjtc000 = false; - } else { - jjtree.popNode(); - } - if (jjte000 instanceof ParseException) { - throw (ParseException)jjte000; - } - if (jjte000 instanceof RuntimeException) { - throw (RuntimeException)jjte000; - } - throw (Error)jjte000; - } finally { -if (jjtc000) { - jjtree.closeNodeScope(jjtn000, true); - } - } - throw new IllegalStateException ("Missing return statement in function"); -} - - final public double ParamList() throws ParseException {/*@bgen(jjtree) ParamList */ - ASTParamList jjtn000 = new ASTParamList(JJTPARAMLIST); - boolean jjtc000 = true; - jjtree.openNodeScope(jjtn000);double num; - try { - jj_consume_token(20); - num = Number(); - jj_consume_token(21); -jjtree.closeNodeScope(jjtn000, true); - jjtc000 = false; -{if ("" != null) return num;} - } catch (Throwable jjte000) { -if (jjtc000) { - jjtree.clearNodeScope(jjtn000); - jjtc000 = false; - } else { - jjtree.popNode(); - } - if (jjte000 instanceof ParseException) { - throw (ParseException)jjte000; - } - if (jjte000 instanceof RuntimeException) { - throw (RuntimeException)jjte000; - } - throw (Error)jjte000; - } finally { -if (jjtc000) { - jjtree.closeNodeScope(jjtn000, true); - } - } - throw new IllegalStateException ("Missing return statement in function"); -} - - final public double Number() throws ParseException {/*@bgen(jjtree) Number */ - ASTNumber jjtn000 = new ASTNumber(JJTNUMBER); - boolean jjtc000 = true; - jjtree.openNodeScope(jjtn000);Token t; - try { - switch (jj_ntk == -1 ? jj_ntk_f() : jj_ntk) { - case FLOAT:{ - t = jj_consume_token(FLOAT); -jjtree.closeNodeScope(jjtn000, true); - jjtc000 = false; -try { - {if ("" != null) return Double.parseDouble(t.image);} - } - catch (Exception e) { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, - "Could not parse double '" + t.image + "'", e); - } - - {if ("" != null) return 0.0;} - break; - } - case INTEGER:{ - t = jj_consume_token(INTEGER); -jjtree.closeNodeScope(jjtn000, true); - jjtc000 = false; -try { - {if ("" != null) return Double.parseDouble(t.image);} - } - catch (Exception e) { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, - "Could not parse double '" + t.image + "'", e); - } - - {if ("" != null) return 0.0;} - break; - } - default: - jj_la1[10] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - } finally { -if (jjtc000) { - jjtree.closeNodeScope(jjtn000, true); - } - } - throw new IllegalStateException ("Missing return statement in function"); -} - - final public int Integer() throws ParseException {/*@bgen(jjtree) Integer */ - ASTInteger jjtn000 = new ASTInteger(JJTINTEGER); - boolean jjtc000 = true; - jjtree.openNodeScope(jjtn000);Token t; - try { - t = jj_consume_token(INTEGER); -jjtree.closeNodeScope(jjtn000, true); - jjtc000 = false; -try { - {if ("" != null) return Integer.parseInt(t.image);} - } - catch (Exception e) { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, - "Could not parse int '" + t.image + "'", e); - } - - {if ("" != null) return 0;} - } finally { -if (jjtc000) { - jjtree.closeNodeScope(jjtn000, true); - } - } - throw new IllegalStateException ("Missing return statement in function"); -} - - private boolean jj_2_1(int xla) - { - jj_la = xla; - jj_scanpos = token; - jj_lastpos = token; - try { return (!jj_3_1()); } - catch(LookaheadSuccess ls) { return true; } - finally { jj_save(0, xla); } - } - - private boolean jj_3R_3() - { - Token xsp; - xsp = jj_scanpos; - if (jj_3R_4()) { - jj_scanpos = xsp; - if (jj_3R_5()) { - jj_scanpos = xsp; - if (jj_3R_6()) { - jj_scanpos = xsp; - if (jj_3R_7()) return true; - } - } - } - return false; - } - - private boolean jj_3R_4() - { - if (jj_3R_8()) return true; - return false; - } - - private boolean jj_3R_9() - { - if (jj_3R_12()) return true; - return false; - } - - private boolean jj_3R_5() - { - if (jj_3R_9()) return true; - return false; - } - - private boolean jj_3R_12() - { - Token xsp; - xsp = jj_scanpos; - if (jj_3R_13()) { - jj_scanpos = xsp; - if (jj_3R_14()) return true; - } - return false; - } - - private boolean jj_3R_13() - { - if (jj_scan_token(FLOAT)) return true; - return false; - } - - private boolean jj_3R_6() - { - if (jj_3R_10()) return true; - return false; - } - - private boolean jj_3R_7() - { - if (jj_3R_11()) return true; - return false; - } - - private boolean jj_3R_2() - { - if (jj_3R_3()) return true; - return false; - } - - private boolean jj_3R_8() - { - if (jj_scan_token(INDEFINITE)) return true; - return false; - } - - private boolean jj_3R_10() - { - if (jj_scan_token(IDENTIFIER)) return true; - return false; - } - - private boolean jj_3_1() - { - if (jj_scan_token(15)) return true; - if (jj_3R_2()) return true; - return false; - } - - private boolean jj_3R_14() - { - if (jj_scan_token(INTEGER)) return true; - return false; - } - - private boolean jj_3R_11() - { - Token xsp; - xsp = jj_scanpos; - if (jj_scan_token(11)) { - jj_scanpos = xsp; - if (jj_scan_token(12)) return true; - } - return false; - } - - /** Generated Token Manager. */ - public AnimTimeParserTokenManager token_source; - SimpleCharStream jj_input_stream; - /** Current token. */ - public Token token; - /** Next token. */ - public Token jj_nt; - private int jj_ntk; - private Token jj_scanpos, jj_lastpos; - private int jj_la; - private int jj_gen; - final private int[] jj_la1 = new int[11]; - static private int[] jj_la1_0; - static { - jj_la1_init_0(); - } - private static void jj_la1_init_0() { - jj_la1_0 = new int[] {0x5f00,0x8000,0x30000,0x30000,0x5f00,0x1800,0x40000,0x42000,0x42000,0x100000,0x300,}; - } - private final JJCalls[] jj_2_rtns = new JJCalls[1]; - private boolean jj_rescan = false; - private int jj_gc = 0; - - /** - * Constructor with InputStream. - * @param stream input stream - */ - public AnimTimeParser(final java.io.InputStream stream) { - this(stream, null); - } - - /** - * Constructor with InputStream and supplied encoding - * @param stream input stream - * @param encoding charset to be used - */ - public AnimTimeParser(final java.io.InputStream stream, final java.nio.charset.Charset encoding) { - jj_input_stream = new SimpleCharStream(stream, encoding, 1, 1); - token_source = new AnimTimeParserTokenManager(jj_input_stream); - token = new Token(); - jj_ntk = -1; - jj_gen = 0; - for (int i = 0; i < 11; i++) jj_la1[i] = -1; - for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); - } - - /** - * Reinitialise - * @param stream input stream - */ - public void ReInit(final java.io.InputStream stream) { - ReInit(stream, null); - } - /** - * Reinitialise - * @param stream input stream - * @param encoding charset to be used - */ - public void ReInit(final java.io.InputStream stream, final java.nio.charset.Charset encoding) { - jj_input_stream.reInit(stream, encoding, 1, 1); - token_source.ReInit(jj_input_stream); - token = new Token(); - jj_ntk = -1; - jj_gen = 0; - for (int i = 0; i < 11; i++) jj_la1[i] = -1; - for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); - } - - /** - * Constructor with InputStream. - * @param stream char stream - */ - public AnimTimeParser(final java.io.Reader stream) { - jj_input_stream = new SimpleCharStream(stream, 1, 1); - token_source = new AnimTimeParserTokenManager(jj_input_stream); - token = new Token(); - jj_ntk = -1; - jj_gen = 0; - for (int i = 0; i < 11; i++) - jj_la1[i] = -1; - for (int i = 0; i < jj_2_rtns.length; i++) - jj_2_rtns[i] = new JJCalls(); - } - - /** - * Reinitialise - * @param stream char stream - */ - public void ReInit(final java.io.Reader stream) { - if (jj_input_stream == null) { - jj_input_stream = new SimpleCharStream(stream, 1, 1); - } else { - jj_input_stream.reInit(stream, 1, 1); - } - if (token_source == null) { - token_source = new AnimTimeParserTokenManager(jj_input_stream); - } - - token_source.ReInit(jj_input_stream); - token = new Token(); - jj_ntk = -1; - jj_gen = 0; - for (int i = 0; i < 11; i++) - jj_la1[i] = -1; - for (int i = 0; i < jj_2_rtns.length; i++) - jj_2_rtns[i] = new JJCalls(); - } - - /** - * Constructor with generated Token Manager. - * @param tm Token manager to use - */ - public AnimTimeParser(final AnimTimeParserTokenManager tm) { - token_source = tm; - token = new Token(); - jj_ntk = -1; - jj_gen = 0; - for (int i = 0; i < 11; i++) jj_la1[i] = -1; - for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); - } - - /** - * Reinitialise - * @param tm Token manager to use - */ - public void ReInit(final AnimTimeParserTokenManager tm) { - token_source = tm; - token = new Token(); - jj_ntk = -1; - jj_gen = 0; - for (int i = 0; i < 11; i++) jj_la1[i] = -1; - for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); - } - - private Token jj_consume_token(final int kind) throws ParseException { - final Token oldToken = token; - if (token.next != null) - token = token.next; - else { - token.next = token_source.getNextToken(); - token = token.next; - } - jj_ntk = -1; - if (token.kind == kind) { - jj_gen++; - if (++jj_gc > 100) { - jj_gc = 0; - for (int i = 0; i < jj_2_rtns.length; i++) { - JJCalls c = jj_2_rtns[i]; - while (c != null) { - if (c.gen < jj_gen) - c.first = null; - c = c.next; - } - } - } - return token; - } - token = oldToken; - jj_kind = kind; - throw generateParseException(); - } - - @SuppressWarnings("serial") - private static final class LookaheadSuccess extends IllegalStateException { } - private final LookaheadSuccess jj_ls = new LookaheadSuccess(); - private boolean jj_scan_token(int kind) { - if (jj_scanpos == jj_lastpos) { - jj_la--; - if (jj_scanpos.next == null) { - jj_lastpos = jj_scanpos = jj_scanpos.next = token_source.getNextToken(); - } else { - jj_lastpos = jj_scanpos = jj_scanpos.next; - } - } else { - jj_scanpos = jj_scanpos.next; - } - if (jj_rescan) { - int i = 0; Token tok = token; - while (tok != null && tok != jj_scanpos) { i++; tok = tok.next; } - if (tok != null) jj_add_error_token(kind, i); - } - if (jj_scanpos.kind != kind) return true; - if (jj_la == 0 && jj_scanpos == jj_lastpos) throw jj_ls; - return false; - } - - - /** - * @return the next Token. - */ - public final Token getNextToken() { - if (token.next != null) - token = token.next; - else - token = token.next = token_source.getNextToken(); - jj_ntk = -1; - jj_gen++; - return token; - } - - /** - * @param index index to be retrieved - * @return the specific Token. - */ - public final Token getToken(final int index) { - Token t = token; - for (int i = 0; i < index; i++) { - if (t.next == null) - t.next = token_source.getNextToken(); - t = t.next; - } - return t; - } - - private int jj_ntk_f() { - jj_nt = token.next; - if (jj_nt == null) { - token.next = token_source.getNextToken(); - jj_ntk = token.next.kind; - return jj_ntk; - } - jj_ntk = jj_nt.kind; - return jj_ntk; - } - - private java.util.List jj_expentries = new java.util.ArrayList<>(); - private int[] jj_expentry; - private int jj_kind = -1; - private int[] jj_lasttokens = new int[100]; - private int jj_endpos; - - private void jj_add_error_token(int kind, int pos) { - if (pos >= 100) { - return; - } - - if (pos == jj_endpos + 1) { - jj_lasttokens[jj_endpos++] = kind; - } else if (jj_endpos != 0) { - jj_expentry = new int[jj_endpos]; - - for (int i = 0; i < jj_endpos; i++) { - jj_expentry[i] = jj_lasttokens[i]; - } - - for (final int[] oldentry : jj_expentries) { - if (oldentry.length == jj_expentry.length) { - boolean isMatched = true; - for (int i = 0; i < jj_expentry.length; i++) { - if (oldentry[i] != jj_expentry[i]) { - isMatched = false; - break; - } - } - if (isMatched) { - jj_expentries.add(jj_expentry); - break; - } - } - } - - if (pos != 0) { - jj_endpos = pos; - jj_lasttokens[jj_endpos - 1] = kind; - } - } -} - - /** - * Generate ParseException. - * @return new Exception object. Never null - */ - public ParseException generateParseException() { - jj_expentries.clear(); - boolean[] la1tokens = new boolean[22]; - if (jj_kind >= 0) { - la1tokens[jj_kind] = true; - jj_kind = -1; - } - for (int i = 0; i < 11; i++) { - if (jj_la1[i] == jj_gen) { - for (int j = 0; j < 32; j++) { - if ((jj_la1_0[i] & (1<false. - */ - public final boolean trace_enabled() { - return false; - } - - /** Enable tracing. */ - public final void enable_tracing() {} - - /** Disable tracing. */ - public final void disable_tracing() {} - - private void jj_rescan_token() { - jj_rescan = true; - for (int i = 0; i < 1; i++) { - try { - JJCalls p = jj_2_rtns[i]; - do { - if (p.gen > jj_gen) { - jj_la = p.arg; - jj_scanpos = p.first; - jj_lastpos = p.first; - switch (i) { - case 0: jj_3_1(); break; - } - } - p = p.next; - } while (p != null); - } catch(LookaheadSuccess ls) { /* ignore */ } - } - jj_rescan = false; - } - - private void jj_save(int index, int xla) { - JJCalls p = jj_2_rtns[index]; - while (p.gen > jj_gen) { - if (p.next == null) { - p.next = new JJCalls(); - p = p.next; - break; - } - p = p.next; - } - p.gen = jj_gen + xla - jj_la; - p.first = token; - p.arg = xla; - } - - static final class JJCalls { - int gen; - Token first; - int arg; - JJCalls next; - } - -} --- a/src/com/kitfox/svg/animation/parser/AnimTimeParser.jjt +++ /dev/null @@ -1,336 +0,0 @@ -/** - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - */ - - -options { - MULTI=true; - STATIC=false; -} - -PARSER_BEGIN(AnimTimeParser) - -package com.kitfox.svg.animation.parser; - -import com.kitfox.svg.SVGConst; -import com.kitfox.svg.animation.TimeBase; -import com.kitfox.svg.animation.TimeCompound; -import com.kitfox.svg.animation.TimeDiscrete; -import com.kitfox.svg.animation.TimeIndefinite; -import com.kitfox.svg.animation.TimeLookup; -import com.kitfox.svg.animation.TimeSum; -import java.io.StringReader; -import java.util.ArrayList; -import java.util.logging.Level; -import java.util.logging.Logger; - -public class AnimTimeParser -{ - /** - * Test the parser - */ - public static void main(String args[]) throws ParseException - { -// AnimTimeParser parser = new AnimTimeParser(System.in); - StringReader reader; - - reader = new StringReader("1:30 + 5ms"); - AnimTimeParser parser = new AnimTimeParser(reader); - TimeBase tc; - - tc = parser.Expr(); - System.err.println("AnimTimeParser eval to " + tc.evalTime()); - - reader = new StringReader("19"); - parser.ReInit(reader); - tc = parser.Expr(); - System.err.println("AnimTimeParser eval to " + tc.evalTime()); - } - -} - -PARSER_END(AnimTimeParser) - - - - -/** - * Tokens - */ - -SKIP : /* WHITE SPACE */ -{ - " " -| "\t" -| "\n" -| "\r" -| "\f" -} - -TOKEN : -{ - < #LETTER: [ "a"-"z", "A"-"Z" ] > -| - < #DIGIT: [ "0"-"9"] > -| - < INTEGER: ()+ > -| - < FLOAT: (["+", "-"])? ((()* "." ()+) | (()+)) (["E", "e"] (["+", "-"])? ()+)? > -| - < INDEFINITE: "indefinite" > -| - < MOUSE_OVER: "mouseover" > -| - < WHEN_NOT_ACTIVE: "whenNotActive" > -| - < UNITS: "ms" | "s" | "min" | "h" > -| - < IDENTIFIER: (||"_"|"-")* > - -} - - - - - - - -/** - * Expression structure - */ - - -TimeBase Expr() : -{ - TimeBase term; - ArrayList list = new ArrayList(); -} -{ - ( term = Sum() - { - list.add(term); - } - )? - ( LOOKAHEAD(2) ";" term = Sum() - { - list.add(term); - } - ) * - (";")? - - { - switch (list.size()) - { - case 0: - return new TimeIndefinite(); - case 1: - return (TimeBase)list.get(0); - default: - return new TimeCompound(list); - } - } -} - -TimeBase Sum() : -{ - Token t = null; - TimeBase t1; - TimeBase t2 = null; -} -{ - t1=Term() ( (t="+" | t="-") t2 = Term() )? - { - if (t2 == null) return t1; - - if (t.image.equals("-")) - { - return new TimeSum(t1, t2, false); - } - else - { - return new TimeSum(t1, t2, true); - } - } -} - - -TimeBase Term() : -{ - TimeBase base; -} -{ - base=IndefiniteTime() - { return base; } - | base=LiteralTime() - { return base; } - | base=LookupTime() - { return base; } - | base=EventTime() - { return base; } -} - -TimeIndefinite IndefiniteTime() : -{} -{ - - { - return new TimeIndefinite(); - } -} - -TimeDiscrete EventTime() : -{} -{ - ( | ) - { - //For now, map all events to the zero time - return new TimeDiscrete(0); - } -} - -TimeDiscrete LiteralTime() : -{ - double t1, t2, t3 = Double.NaN, value; - Token t; -} -{ - t1=Number() - { - value = t1; - } - ( - - (":" t2=Number() (":" t3=Number())? - { - //Return clock time format (convert to seconds) - if (Double.isNaN(t3)) - { - value = t1 * 60 + t2; - } - else - { - value = t1 * 3600 + t2 * 60 + t3; - } - } - ) - - | - - (t= - { - //Return units format (convert to seconds) - if (t.image.equals("ms")) value = t1 / 1000; - if (t.image.equals("min")) value = t1 * 60; - if (t.image.equals("h")) value = t1 * 3600; - } - ) - )? - { - return new TimeDiscrete(value); - } -} - - -TimeLookup LookupTime() : -{ - double paramNum = 0.0; - Token node, event; -} -{ - node= "." event= (paramNum=ParamList())? - { - return new TimeLookup(null, node.image, event.image, "" + paramNum); - } -} - -double ParamList() : -{ - double num; -} -{ - "(" num=Number() ")" - { - return num; - } -} - -double Number() : -{ - Token t; -} -{ - t= - { - try { - return Double.parseDouble(t.image); - } - catch (Exception e) { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, - "Could not parse double '" + t.image + "'", e); - } - - return 0.0; - } - | t= - { - try { - return Double.parseDouble(t.image); - } - catch (Exception e) { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, - "Could not parse double '" + t.image + "'", e); - } - - return 0.0; - } -} - -int Integer() : -{ - Token t; -} -{ - t= - { - try { - return Integer.parseInt(t.image); - } - catch (Exception e) { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, - "Could not parse int '" + t.image + "'", e); - } - - return 0; - } -} - --- a/src/com/kitfox/svg/animation/parser/AnimTimeParserConstants.java +++ /dev/null @@ -1,61 +0,0 @@ -/* Generated by: JJTree&ParserGeneratorCC: Do not edit this line. AnimTimeParserConstants.java */ -package com.kitfox.svg.animation.parser; - - -/** - * Token literal values and constants. - * Generated by com.helger.pgcc.output.java.OtherFilesGenJava#start() - */ -public interface AnimTimeParserConstants { - - /** End of File. */ - int EOF = 0; - /** RegularExpression Id. */ - int LETTER = 6; - /** RegularExpression Id. */ - int DIGIT = 7; - /** RegularExpression Id. */ - int INTEGER = 8; - /** RegularExpression Id. */ - int FLOAT = 9; - /** RegularExpression Id. */ - int INDEFINITE = 10; - /** RegularExpression Id. */ - int MOUSE_OVER = 11; - /** RegularExpression Id. */ - int WHEN_NOT_ACTIVE = 12; - /** RegularExpression Id. */ - int UNITS = 13; - /** RegularExpression Id. */ - int IDENTIFIER = 14; - - /** Lexical state. */ - int DEFAULT = 0; - - /** Literal token values. */ - String[] tokenImage = { - "", - "\" \"", - "\"\\t\"", - "\"\\n\"", - "\"\\r\"", - "\"\\f\"", - "", - "", - "", - "", - "\"indefinite\"", - "\"mouseover\"", - "\"whenNotActive\"", - "", - "", - "\";\"", - "\"+\"", - "\"-\"", - "\":\"", - "\".\"", - "\"(\"", - "\")\"", - }; - -} --- a/src/com/kitfox/svg/animation/parser/AnimTimeParserTokenManager.java +++ /dev/null @@ -1,866 +0,0 @@ -/* AnimTimeParserTokenManager.java */ -/* Generated by: JJTree&ParserGeneratorCC: Do not edit this line. AnimTimeParserTokenManager.java */ -package com.kitfox.svg.animation.parser; -import com.kitfox.svg.SVGConst; -import com.kitfox.svg.animation.TimeBase; -import com.kitfox.svg.animation.TimeCompound; -import com.kitfox.svg.animation.TimeDiscrete; -import com.kitfox.svg.animation.TimeIndefinite; -import com.kitfox.svg.animation.TimeLookup; -import com.kitfox.svg.animation.TimeSum; -import java.io.StringReader; -import java.util.ArrayList; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** Token Manager. */ -@SuppressWarnings ("unused") -public class AnimTimeParserTokenManager implements AnimTimeParserConstants { -private final int jjStopStringLiteralDfa_0(int pos, long active0){ - switch (pos) - { - case 0: - if ((active0 & 0x30000L) != 0x0L) - return 6; - if ((active0 & 0x800L) != 0x0L) - { - jjmatchedKind = 14; - return 13; - } - if ((active0 & 0x1400L) != 0x0L) - { - jjmatchedKind = 14; - return 11; - } - if ((active0 & 0x80000L) != 0x0L) - return 2; - return -1; - case 1: - if ((active0 & 0x1c00L) != 0x0L) - { - jjmatchedKind = 14; - jjmatchedPos = 1; - return 11; - } - return -1; - case 2: - if ((active0 & 0x1c00L) != 0x0L) - { - jjmatchedKind = 14; - jjmatchedPos = 2; - return 11; - } - return -1; - case 3: - if ((active0 & 0x1c00L) != 0x0L) - { - jjmatchedKind = 14; - jjmatchedPos = 3; - return 11; - } - return -1; - case 4: - if ((active0 & 0x1c00L) != 0x0L) - { - jjmatchedKind = 14; - jjmatchedPos = 4; - return 11; - } - return -1; - case 5: - if ((active0 & 0x1c00L) != 0x0L) - { - jjmatchedKind = 14; - jjmatchedPos = 5; - return 11; - } - return -1; - case 6: - if ((active0 & 0x1c00L) != 0x0L) - { - jjmatchedKind = 14; - jjmatchedPos = 6; - return 11; - } - return -1; - case 7: - if ((active0 & 0x1c00L) != 0x0L) - { - jjmatchedKind = 14; - jjmatchedPos = 7; - return 11; - } - return -1; - case 8: - if ((active0 & 0x800L) != 0x0L) - return 11; - if ((active0 & 0x1400L) != 0x0L) - { - jjmatchedKind = 14; - jjmatchedPos = 8; - return 11; - } - return -1; - case 9: - if ((active0 & 0x1000L) != 0x0L) - { - jjmatchedKind = 14; - jjmatchedPos = 9; - return 11; - } - if ((active0 & 0x400L) != 0x0L) - return 11; - return -1; - case 10: - if ((active0 & 0x1000L) != 0x0L) - { - jjmatchedKind = 14; - jjmatchedPos = 10; - return 11; - } - return -1; - case 11: - if ((active0 & 0x1000L) != 0x0L) - { - jjmatchedKind = 14; - jjmatchedPos = 11; - return 11; - } - return -1; - default : - return -1; - } -} -private final int jjStartNfa_0(int pos, long active0){ - return jjMoveNfa_0(jjStopStringLiteralDfa_0(pos, active0), pos + 1); -} -private int jjStopAtPos(int pos, int kind) -{ - jjmatchedKind = kind; - jjmatchedPos = pos; - return pos + 1; -} -private int jjMoveStringLiteralDfa0_0(){ - switch(curChar) - { - case '(': - return jjStopAtPos(0, 20); - case ')': - return jjStopAtPos(0, 21); - case '+': - return jjStartNfaWithStates_0(0, 16, 6); - case '-': - return jjStartNfaWithStates_0(0, 17, 6); - case '.': - return jjStartNfaWithStates_0(0, 19, 2); - case ':': - return jjStopAtPos(0, 18); - case ';': - return jjStopAtPos(0, 15); - case 'i': - return jjMoveStringLiteralDfa1_0(0x400L); - case 'm': - return jjMoveStringLiteralDfa1_0(0x800L); - case 'w': - return jjMoveStringLiteralDfa1_0(0x1000L); - default : - return jjMoveNfa_0(0, 0); - } -} -private int jjMoveStringLiteralDfa1_0(long active0){ - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { - jjStopStringLiteralDfa_0(0, active0); - return 1; - } - switch(curChar) - { - case 'h': - return jjMoveStringLiteralDfa2_0(active0, 0x1000L); - case 'n': - return jjMoveStringLiteralDfa2_0(active0, 0x400L); - case 'o': - return jjMoveStringLiteralDfa2_0(active0, 0x800L); - default : - break; - } - return jjStartNfa_0(0, active0); -} -private int jjMoveStringLiteralDfa2_0(long old0, long active0){ - if (((active0 &= old0)) == 0L) - return jjStartNfa_0(0, old0); - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { - jjStopStringLiteralDfa_0(1, active0); - return 2; - } - switch(curChar) - { - case 'd': - return jjMoveStringLiteralDfa3_0(active0, 0x400L); - case 'e': - return jjMoveStringLiteralDfa3_0(active0, 0x1000L); - case 'u': - return jjMoveStringLiteralDfa3_0(active0, 0x800L); - default : - break; - } - return jjStartNfa_0(1, active0); -} -private int jjMoveStringLiteralDfa3_0(long old0, long active0){ - if (((active0 &= old0)) == 0L) - return jjStartNfa_0(1, old0); - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { - jjStopStringLiteralDfa_0(2, active0); - return 3; - } - switch(curChar) - { - case 'e': - return jjMoveStringLiteralDfa4_0(active0, 0x400L); - case 'n': - return jjMoveStringLiteralDfa4_0(active0, 0x1000L); - case 's': - return jjMoveStringLiteralDfa4_0(active0, 0x800L); - default : - break; - } - return jjStartNfa_0(2, active0); -} -private int jjMoveStringLiteralDfa4_0(long old0, long active0){ - if (((active0 &= old0)) == 0L) - return jjStartNfa_0(2, old0); - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { - jjStopStringLiteralDfa_0(3, active0); - return 4; - } - switch(curChar) - { - case 'N': - return jjMoveStringLiteralDfa5_0(active0, 0x1000L); - case 'e': - return jjMoveStringLiteralDfa5_0(active0, 0x800L); - case 'f': - return jjMoveStringLiteralDfa5_0(active0, 0x400L); - default : - break; - } - return jjStartNfa_0(3, active0); -} -private int jjMoveStringLiteralDfa5_0(long old0, long active0){ - if (((active0 &= old0)) == 0L) - return jjStartNfa_0(3, old0); - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { - jjStopStringLiteralDfa_0(4, active0); - return 5; - } - switch(curChar) - { - case 'i': - return jjMoveStringLiteralDfa6_0(active0, 0x400L); - case 'o': - return jjMoveStringLiteralDfa6_0(active0, 0x1800L); - default : - break; - } - return jjStartNfa_0(4, active0); -} -private int jjMoveStringLiteralDfa6_0(long old0, long active0){ - if (((active0 &= old0)) == 0L) - return jjStartNfa_0(4, old0); - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { - jjStopStringLiteralDfa_0(5, active0); - return 6; - } - switch(curChar) - { - case 'n': - return jjMoveStringLiteralDfa7_0(active0, 0x400L); - case 't': - return jjMoveStringLiteralDfa7_0(active0, 0x1000L); - case 'v': - return jjMoveStringLiteralDfa7_0(active0, 0x800L); - default : - break; - } - return jjStartNfa_0(5, active0); -} -private int jjMoveStringLiteralDfa7_0(long old0, long active0){ - if (((active0 &= old0)) == 0L) - return jjStartNfa_0(5, old0); - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { - jjStopStringLiteralDfa_0(6, active0); - return 7; - } - switch(curChar) - { - case 'A': - return jjMoveStringLiteralDfa8_0(active0, 0x1000L); - case 'e': - return jjMoveStringLiteralDfa8_0(active0, 0x800L); - case 'i': - return jjMoveStringLiteralDfa8_0(active0, 0x400L); - default : - break; - } - return jjStartNfa_0(6, active0); -} -private int jjMoveStringLiteralDfa8_0(long old0, long active0){ - if (((active0 &= old0)) == 0L) - return jjStartNfa_0(6, old0); - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { - jjStopStringLiteralDfa_0(7, active0); - return 8; - } - switch(curChar) - { - case 'c': - return jjMoveStringLiteralDfa9_0(active0, 0x1000L); - case 'r': - if ((active0 & 0x800L) != 0x0L) - return jjStartNfaWithStates_0(8, 11, 11); - break; - case 't': - return jjMoveStringLiteralDfa9_0(active0, 0x400L); - default : - break; - } - return jjStartNfa_0(7, active0); -} -private int jjMoveStringLiteralDfa9_0(long old0, long active0){ - if (((active0 &= old0)) == 0L) - return jjStartNfa_0(7, old0); - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { - jjStopStringLiteralDfa_0(8, active0); - return 9; - } - switch(curChar) - { - case 'e': - if ((active0 & 0x400L) != 0x0L) - return jjStartNfaWithStates_0(9, 10, 11); - break; - case 't': - return jjMoveStringLiteralDfa10_0(active0, 0x1000L); - default : - break; - } - return jjStartNfa_0(8, active0); -} -private int jjMoveStringLiteralDfa10_0(long old0, long active0){ - if (((active0 &= old0)) == 0L) - return jjStartNfa_0(8, old0); - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { - jjStopStringLiteralDfa_0(9, active0); - return 10; - } - switch(curChar) - { - case 'i': - return jjMoveStringLiteralDfa11_0(active0, 0x1000L); - default : - break; - } - return jjStartNfa_0(9, active0); -} -private int jjMoveStringLiteralDfa11_0(long old0, long active0){ - if (((active0 &= old0)) == 0L) - return jjStartNfa_0(9, old0); - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { - jjStopStringLiteralDfa_0(10, active0); - return 11; - } - switch(curChar) - { - case 'v': - return jjMoveStringLiteralDfa12_0(active0, 0x1000L); - default : - break; - } - return jjStartNfa_0(10, active0); -} -private int jjMoveStringLiteralDfa12_0(long old0, long active0){ - if (((active0 &= old0)) == 0L) - return jjStartNfa_0(10, old0); - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { - jjStopStringLiteralDfa_0(11, active0); - return 12; - } - switch(curChar) - { - case 'e': - if ((active0 & 0x1000L) != 0x0L) - return jjStartNfaWithStates_0(12, 12, 11); - break; - default : - break; - } - return jjStartNfa_0(11, active0); -} -private int jjStartNfaWithStates_0(int pos, int kind, int state) -{ - jjmatchedKind = kind; - jjmatchedPos = pos; - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { return pos + 1; } - return jjMoveNfa_0(state, pos + 1); -} -private int jjMoveNfa_0(int startState, int curPos) -{ - int startsAt = 0; - jjnewStateCnt = 18; - int i = 1; - jjstateSet[0] = startState; - int kind = 0x7fffffff; - for (;;) - { - if (++jjround == 0x7fffffff) - ReInitRounds(); - if (curChar < 64) - { - long l = 1L << curChar; - do - { - switch(jjstateSet[--i]) - { - case 0: - if ((0x3ff000000000000L & l) != 0x0L) - { - if (kind > 8) - kind = 8; - { jjCheckNAddStates(0, 4); } - } - else if ((0x280000000000L & l) != 0x0L) - { jjCheckNAddTwoStates(1, 6); } - else if (curChar == 46) - { jjCheckNAdd(2); } - break; - case 6: - if ((0x3ff000000000000L & l) != 0x0L) - { - if (kind > 9) - kind = 9; - { jjCheckNAddStates(5, 8); } - } - else if (curChar == 46) - { jjCheckNAdd(2); } - break; - case 13: - case 11: - if ((0x3ff200000000000L & l) == 0x0L) - break; - if (kind > 14) - kind = 14; - { jjCheckNAdd(11); } - break; - case 1: - if (curChar == 46) - { jjCheckNAdd(2); } - break; - case 2: - if ((0x3ff000000000000L & l) == 0x0L) - break; - if (kind > 9) - kind = 9; - { jjCheckNAddTwoStates(2, 3); } - break; - case 4: - if ((0x280000000000L & l) != 0x0L) - { jjCheckNAdd(5); } - break; - case 5: - if ((0x3ff000000000000L & l) == 0x0L) - break; - if (kind > 9) - kind = 9; - { jjCheckNAdd(5); } - break; - case 7: - if ((0x3ff000000000000L & l) != 0x0L) - { jjCheckNAddTwoStates(7, 1); } - break; - case 8: - if ((0x3ff000000000000L & l) == 0x0L) - break; - if (kind > 9) - kind = 9; - { jjCheckNAddTwoStates(8, 3); } - break; - case 16: - if ((0x3ff000000000000L & l) == 0x0L) - break; - if (kind > 8) - kind = 8; - { jjCheckNAddStates(0, 4); } - break; - case 17: - if ((0x3ff000000000000L & l) == 0x0L) - break; - if (kind > 8) - kind = 8; - { jjCheckNAdd(17); } - break; - default : break; - } - } while(i != startsAt); - } - else if (curChar < 128) - { - long l = 1L << (curChar & 077); - do - { - switch(jjstateSet[--i]) - { - case 0: - if ((0x7fffffe07fffffeL & l) != 0x0L) - { - if (kind > 14) - kind = 14; - { jjCheckNAdd(11); } - } - if ((0x8010000000000L & l) != 0x0L) - { - if (kind > 13) - kind = 13; - } - else if (curChar == 109) - { jjAddStates(9, 10); } - break; - case 13: - if ((0x7fffffe87fffffeL & l) != 0x0L) - { - if (kind > 14) - kind = 14; - { jjCheckNAdd(11); } - } - if (curChar == 105) - jjstateSet[jjnewStateCnt++] = 14; - else if (curChar == 115) - { - if (kind > 13) - kind = 13; - } - break; - case 3: - if ((0x2000000020L & l) != 0x0L) - { jjAddStates(11, 12); } - break; - case 9: - if ((0x8010000000000L & l) != 0x0L && kind > 13) - kind = 13; - break; - case 10: - if ((0x7fffffe07fffffeL & l) == 0x0L) - break; - if (kind > 14) - kind = 14; - { jjCheckNAdd(11); } - break; - case 11: - if ((0x7fffffe87fffffeL & l) == 0x0L) - break; - if (kind > 14) - kind = 14; - { jjCheckNAdd(11); } - break; - case 12: - if (curChar == 109) - { jjAddStates(9, 10); } - break; - case 14: - if (curChar == 110 && kind > 13) - kind = 13; - break; - case 15: - if (curChar == 105) - jjstateSet[jjnewStateCnt++] = 14; - break; - default : break; - } - } while(i != startsAt); - } - else - { - int i2 = (curChar & 0xff) >> 6; - long l2 = 1L << (curChar & 077); - do - { - switch(jjstateSet[--i]) - { - default : break; - } - } while(i != startsAt); - } - if (kind != 0x7fffffff) - { - jjmatchedKind = kind; - jjmatchedPos = curPos; - kind = 0x7fffffff; - } - ++curPos; - i = jjnewStateCnt; - jjnewStateCnt = startsAt; - startsAt = 18 - jjnewStateCnt; - if (i == startsAt) - return curPos; - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { return curPos; } - } -} - -/** Token literal values. */ -public static final String[] jjstrLiteralImages = { -"", null, null, null, null, null, null, null, null, null, -"\151\156\144\145\146\151\156\151\164\145", "\155\157\165\163\145\157\166\145\162", -"\167\150\145\156\116\157\164\101\143\164\151\166\145", null, null, "\73", "\53", "\55", "\72", "\56", "\50", "\51", }; -protected Token jjFillToken() -{ - final Token t; - final String curTokenImage; - final int beginLine; - final int endLine; - final int beginColumn; - final int endColumn; - String im = jjstrLiteralImages[jjmatchedKind]; - curTokenImage = im == null ? input_stream.getImage() : im; - beginLine = input_stream.getBeginLine(); - beginColumn = input_stream.getBeginColumn(); - endLine = input_stream.getEndLine(); - endColumn = input_stream.getEndColumn(); - t = Token.newToken(jjmatchedKind); - t.kind = jjmatchedKind; - t.image = curTokenImage; - - t.beginLine = beginLine; - t.endLine = endLine; - t.beginColumn = beginColumn; - t.endColumn = endColumn; - - return t; -} -static final int[] jjnextStates = { - 17, 7, 1, 8, 3, 7, 1, 8, 3, 13, 15, 4, 5, -}; - -int curLexState = 0; -int defaultLexState = 0; -int jjnewStateCnt; -int jjround; -int jjmatchedPos; -int jjmatchedKind; - -/** Get the next Token. */ -public Token getNextToken() -{ - Token matchedToken; - int curPos = 0; - - EOFLoop: - for (;;) - { - try - { - curChar = input_stream.beginToken(); - } - catch(final Exception e) - { - jjmatchedKind = 0; - jjmatchedPos = -1; - matchedToken = jjFillToken(); - return matchedToken; - } - - try { - input_stream.backup(0); - while (curChar <= 32 && (0x100003600L & (1L << curChar)) != 0x0L) - curChar = input_stream.beginToken(); - } - catch (final java.io.IOException e1) { - continue EOFLoop; - } - jjmatchedKind = 0x7fffffff; - jjmatchedPos = 0; - curPos = jjMoveStringLiteralDfa0_0(); - if (jjmatchedKind != 0x7fffffff) - { - if (jjmatchedPos + 1 < curPos) - input_stream.backup(curPos - jjmatchedPos - 1); - if ((jjtoToken[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L) - { - matchedToken = jjFillToken(); - return matchedToken; - } - else - { - continue EOFLoop; - } - } - int error_line = input_stream.getEndLine(); - int error_column = input_stream.getEndColumn(); - String error_after = null; - boolean EOFSeen = false; - try { - input_stream.readChar(); - input_stream.backup(1); - } - catch (final java.io.IOException e1) { - EOFSeen = true; - error_after = curPos <= 1 ? "" : input_stream.getImage(); - if (curChar == '\n' || curChar == '\r') { - error_line++; - error_column = 0; - } - else - error_column++; - } - if (!EOFSeen) { - input_stream.backup(1); - error_after = curPos <= 1 ? "" : input_stream.getImage(); - } - throw new TokenMgrException(EOFSeen, curLexState, error_line, error_column, error_after, curChar, TokenMgrException.LEXICAL_ERROR); - } -} - -void SkipLexicalActions(Token matchedToken) -{ - switch(jjmatchedKind) - { - default : - break; - } -} -void MoreLexicalActions() -{ - jjimageLen += (lengthOfMatch = jjmatchedPos + 1); - switch(jjmatchedKind) - { - default : - break; - } -} -void TokenLexicalActions(Token matchedToken) -{ - switch(jjmatchedKind) - { - default : - break; - } -} -private void jjCheckNAdd(int state) -{ - if (jjrounds[state] != jjround) - { - jjstateSet[jjnewStateCnt++] = state; - jjrounds[state] = jjround; - } -} -private void jjAddStates(int start, int end) -{ - do { - jjstateSet[jjnewStateCnt++] = jjnextStates[start]; - } while (start++ != end); -} -private void jjCheckNAddTwoStates(int state1, int state2) -{ - jjCheckNAdd(state1); - jjCheckNAdd(state2); -} - -private void jjCheckNAddStates(int start, int end) -{ - do { - jjCheckNAdd(jjnextStates[start]); - } while (start++ != end); -} - - /** Constructor. */ - public AnimTimeParserTokenManager(SimpleCharStream stream){ - input_stream = stream; - } - - /** Constructor. */ - public AnimTimeParserTokenManager (SimpleCharStream stream, int lexState){ - ReInit(stream); - SwitchTo(lexState); - } - - /** Reinitialise parser. */ - - public void ReInit(SimpleCharStream stream) - { - - - jjmatchedPos = - jjnewStateCnt = - 0; - curLexState = defaultLexState; - input_stream = stream; - ReInitRounds(); - } - - private void ReInitRounds() - { - int i; - jjround = 0x80000001; - for (i = 18; i-- > 0;) - jjrounds[i] = 0x80000000; - } - - /** Reinitialise parser. */ - public void ReInit(SimpleCharStream stream, int lexState) - { - ReInit(stream); - SwitchTo(lexState); - } - - /** Switch to specified lex state. */ - public void SwitchTo(int lexState) - { - if (lexState >= 1 || lexState < 0) - throw new TokenMgrException("Error: Ignoring invalid lexical state : " + lexState + ". State unchanged.", TokenMgrException.INVALID_LEXICAL_STATE); - else - curLexState = lexState; - } - - -/** Lexer state names. */ -public static final String[] lexStateNames = { - "DEFAULT", -}; - -/** Lex State array. */ -public static final int[] jjnewLexState = { - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -}; -static final long[] jjtoToken = { - 0x3fff01L, -}; -static final long[] jjtoSkip = { - 0x3eL, -}; -static final long[] jjtoSpecial = { - 0x0L, -}; -static final long[] jjtoMore = { - 0x0L, -}; - protected SimpleCharStream input_stream; - - private final int[] jjrounds = new int[18]; - private final int[] jjstateSet = new int[2 * 18]; - private final StringBuilder jjimage = new StringBuilder(); - private StringBuilder image = jjimage; - private int jjimageLen; - private int lengthOfMatch; - protected int curChar; -} --- a/src/com/kitfox/svg/animation/parser/AnimTimeParserTreeConstants.java +++ /dev/null @@ -1,31 +0,0 @@ -/* Generated by: ParserGeneratorCC: Do not edit this line. AnimTimeParserTreeConstants.java Version 1.1.0 */ -package com.kitfox.svg.animation.parser; - -public interface AnimTimeParserTreeConstants -{ - public int JJTEXPR = 0; - public int JJTSUM = 1; - public int JJTTERM = 2; - public int JJTINDEFINITETIME = 3; - public int JJTEVENTTIME = 4; - public int JJTLITERALTIME = 5; - public int JJTLOOKUPTIME = 6; - public int JJTPARAMLIST = 7; - public int JJTNUMBER = 8; - public int JJTINTEGER = 9; - - - public String[] jjtNodeName = { - "Expr", - "Sum", - "Term", - "IndefiniteTime", - "EventTime", - "LiteralTime", - "LookupTime", - "ParamList", - "Number", - "Integer", - }; -} -/* ParserGeneratorCC - OriginalChecksum=b430612e19cf25b4f478626670ac4129 (do not edit this line) */ --- a/src/com/kitfox/svg/animation/parser/CharStream.java +++ /dev/null @@ -1,123 +0,0 @@ -/* Generated by: ParserGeneratorCC: Do not edit this line. CharStream.java Version 1.1 */ -/* ParserGeneratorCCOptions:SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ -package com.kitfox.svg.animation.parser; - -/** - * This interface describes a character stream that maintains line and - * column number positions of the characters. It also has the capability - * to backup the stream to some extent. An implementation of this - * interface is used in the TokenManager implementation generated by - * JavaCCParser. - * - * All the methods except backup can be implemented in any fashion. backup - * needs to be implemented correctly for the correct operation of the lexer. - * Rest of the methods are all used to get information like line number, - * column number and the String that constitutes a token and are not used - * by the lexer. Hence their implementation won't affect the generated lexer's - * operation. - */ - -public -interface CharStream { - /** - * Get the next character from the selected input. The method - * of selecting the input is the responsibility of the class - * implementing this interface. - * @return the next character from the selected input - * @throws java.io.IOException on IO error - */ - char readChar() throws java.io.IOException; - - /** - * @return the column number of the first character for current token (being - * matched after the last call to beginToken). - */ - int getBeginColumn(); - - /** - * @return the line number of the first character for current token (being - * matched after the last call to BeginToken). - */ - int getBeginLine(); - - /** - * @return the column number of the last character for current token (being - * matched after the last call to BeginToken). - */ - int getEndColumn(); - - /** - * @return the line number of the last character for current token (being - * matched after the last call to BeginToken). - */ - int getEndLine(); - - /** - * Backs up the input stream by amount steps. Lexer calls this method if it - * had already read some characters, but could not use them to match a - * (longer) token. So, they will be used again as the prefix of the next - * token and it is the implemetation's responsibility to do this right. - * @param amount Number of chars to back up. - */ - void backup(int amount); - - /** - * @return the next character that marks the beginning of the next token. - * All characters must remain in the buffer between two successive calls - * to this method to implement backup correctly. - */ - char beginToken() throws java.io.IOException; - - /** - * @return a string made up of characters from the marked token beginning - * to the current buffer position. Implementations have the choice of returning - * anything that they want to. For example, for efficiency, one might decide - * to just return null, which is a valid implementation. - */ - String getImage(); - - /** - * @return an array of characters that make up the suffix of length 'len' for - * the currently matched token. This is used to build up the matched string - * for use in actions in the case of MORE. A simple and inefficient - * implementation of this is as follows: - *
-   *   {
-   *      String t = getImage();
-   *      return t.substring(t.length() - len, t.length()).toCharArray();
-   *   }
-   * 
- */ - char[] getSuffix(int len); - - /** - * The lexer calls this function to indicate that it is done with the stream - * and hence implementations can free any resources held by this class. - * Again, the body of this function can be just empty and it will not - * affect the lexer's operation. - */ - void done(); - - /** - * Set the tab size to use. - * @param i spaces per tab - */ - void setTabSize(int i); - - /** - * @return Current tab size. - */ - int getTabSize(); - - /** - * Enable or disable line number and column number tracking. - * @param trackLineColumn true to track it, false to not do it. - */ - void setTrackLineColumn(boolean trackLineColumn); - - /** - * @return true if line number and column numbers should be tracked. - */ - boolean isTrackLineColumn(); -} -/* ParserGeneratorCC - OriginalChecksum=21cf8c5827877a706ff3cff3e9605b41 (do not edit this line) */ --- a/src/com/kitfox/svg/animation/parser/JJTAnimTimeParserState.java +++ /dev/null @@ -1,125 +0,0 @@ -/* Generated by: ParserGeneratorCC: Do not edit this line. JJTAnimTimeParserState.java Version 1.1.0 */ -package com.kitfox.svg.animation.parser; - -public class JJTAnimTimeParserState implements java.io.Serializable { - private java.util.List nodes; - private java.util.List marks; - - /* number of nodes on stack */ - private int sp; - /* current mark */ - private int mk; - private boolean node_created; - - public JJTAnimTimeParserState() { - nodes = new java.util.ArrayList<>(); - marks = new java.util.ArrayList<>(); - sp = 0; - mk = 0; - } - - /* Determines whether the current node was actually closed and - pushed. This should only be called in the final user action of a - node scope. */ - public boolean nodeCreated() { - return node_created; - } - - /* Call this to reinitialize the node stack. It is called - automatically by the parser's ReInit() method. */ - public void reset() { - nodes.clear(); - marks.clear(); - sp = 0; - mk = 0; - } - - /* Returns the root node of the AST. It only makes sense to call - this after a successful parse. */ - public Node rootNode() { - return nodes.get(0); - } - - /* Pushes a node on to the stack. */ - public void pushNode(Node n) { - nodes.add(n); - ++sp; - } - - /* Returns the node on the top of the stack, and remove it from the - stack. */ - public Node popNode() { - --sp; - if (sp < mk) { - mk = marks.remove(marks.size()-1).intValue(); - } - return nodes.remove(nodes.size()-1); - } - - /* Returns the node currently on the top of the stack. */ - public Node peekNode() { - return nodes.get(nodes.size()-1); - } - - /* Returns the number of children on the stack in the current node - scope. */ - public int nodeArity() { - return sp - mk; - } - - /* Parameter is currently unused. */ - public void clearNodeScope(@SuppressWarnings("unused") final Node n) { - while (sp > mk) { - popNode(); - } - mk = marks.remove(marks.size()-1).intValue(); - } - - public void openNodeScope(final Node n) { - marks.add(Integer.valueOf(mk)); - mk = sp; - n.jjtOpen(); - } - - /* A definite node is constructed from a specified number of - children. That number of nodes are popped from the stack and - made the children of the definite node. Then the definite node - is pushed on to the stack. */ - public void closeNodeScope(final Node n, final int numIn) { - mk = marks.remove(marks.size()-1).intValue(); - int num = numIn; - while (num-- > 0) { - Node c = popNode(); - c.jjtSetParent(n); - n.jjtAddChild(c, num); - } - n.jjtClose(); - pushNode(n); - node_created = true; - } - - - /* A conditional node is constructed if its condition is true. All - the nodes that have been pushed since the node was opened are - made children of the conditional node, which is then pushed - on to the stack. If the condition is false the node is not - constructed and they are left on the stack. */ - public void closeNodeScope(final Node n, final boolean condition) { - if (condition) { - int a = nodeArity(); - mk = marks.remove(marks.size()-1).intValue(); - while (a-- > 0) { - final Node c = popNode(); - c.jjtSetParent(n); - n.jjtAddChild(c, a); - } - n.jjtClose(); - pushNode(n); - node_created = true; - } else { - mk = marks.remove(marks.size()-1).intValue(); - node_created = false; - } - } -} -/* ParserGeneratorCC - OriginalChecksum=f8707994805484f7a2bfd76cc1286232 (do not edit this line) */ --- a/src/com/kitfox/svg/animation/parser/Node.java +++ /dev/null @@ -1,52 +0,0 @@ -/* Generated by: JJTree: Do not edit this line. Node.java Version 1.1 */ -/* ParserGeneratorCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=false,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ -package com.kitfox.svg.animation.parser; - -/* All AST nodes must implement this interface. It provides basic - machinery for constructing the parent and child relationships - between nodes. */ - -public -interface Node extends java.io.Serializable { - /** This method is called after the node has been made the current - node. It indicates that child nodes can now be added to it. */ - void jjtOpen(); - - /** This method is called after all the child nodes have been - added. */ - void jjtClose(); - - /** - * Set the parent node of this node - * @param n parent node to set - */ - void jjtSetParent(Node n); - - /** - * @return parent node - */ - Node jjtGetParent(); - - /** - * This method tells the node to add its argument to the node's - * list of children. - * @param n node to add as a child - * @param i zero-based index where to add the child - */ - void jjtAddChild(Node n, int i); - - /** - * This method returns a child node. The children are numbered - * from zero, left to right. - * @param i zero-baeed child index - */ - Node jjtGetChild(int i); - - /** - * @return the number of children the node has. Always ≥ 0. - */ - int jjtGetNumChildren(); - - int getId(); -} -/* ParserGeneratorCC - OriginalChecksum=d890e23b63691941d0501f37ec800a77 (do not edit this line) */ --- a/src/com/kitfox/svg/animation/parser/ParseException.java +++ /dev/null @@ -1,189 +0,0 @@ -/* Generated by: ParserGeneratorCC: Do not edit this line. ParseException.java Version 1.1 */ -/* ParserGeneratorCCOptions:KEEP_LINE_COLUMN=true */ -package com.kitfox.svg.animation.parser; - -/** - * This exception is thrown when parse errors are encountered. - * You can explicitly create objects of this exception type by - * calling the method generateParseException in the generated - * parser. - * - * You can modify this class to customize your error reporting - * mechanisms so long as you retain the public fields. - */ -public class ParseException extends Exception { - /** - * The end of line string for this machine. - */ - protected static final String EOL = System.getProperty("line.separator", "\n"); - - /** - * This constructor is used by the method "generateParseException" - * in the generated parser. Calling this constructor generates - * a new object of this type with the fields "currentToken", - * "expectedTokenSequences", and "tokenImage" set. - */ - public ParseException(final Token currentTokenVal, - final int[][] expectedTokenSequencesVal, - final String[] tokenImageVal) - { - super(_initialise(currentTokenVal, expectedTokenSequencesVal, tokenImageVal)); - currentToken = currentTokenVal; - expectedTokenSequences = expectedTokenSequencesVal; - tokenImage = tokenImageVal; - } - - /** - * The following constructors are for use by you for whatever - * purpose you can think of. Constructing the exception in this - * manner makes the exception behave in the normal way - i.e., as - * documented in the class "Throwable". The fields "errorToken", - * "expectedTokenSequences", and "tokenImage" do not contain - * relevant information. The JavaCC generated code does not use - * these constructors. - */ - - public ParseException() { - super(); - } - - /** Constructor with message. */ - public ParseException(String message) { - super(message); - } - - - /** - * This is the last token that has been consumed successfully. If - * this object has been created due to a parse error, the token - * followng this token will (therefore) be the first error token. - */ - public Token currentToken; - - /** - * Each entry in this array is an array of integers. Each array - * of integers represents a sequence of tokens (by their ordinal - * values) that is expected at this point of the parse. - */ - public int[][] expectedTokenSequences; - - /** - * This is a reference to the "tokenImage" array of the generated - * parser within which the parse error occurred. This array is - * defined in the generated ...Constants interface. - */ - public String[] tokenImage; - - /** - * It uses "currentToken" and "expectedTokenSequences" to generate a parse - * error message and returns it. If this object has been created - * due to a parse error, and you do not catch it (it gets thrown - * from the parser) the correct error message - * gets displayed. - */ - private static String _initialise(final Token currentToken, - final int[][] expectedTokenSequences, - final String[] tokenImage) - { - StringBuilder expected = new StringBuilder(); - int maxSize = 0; - for (int i = 0; i < expectedTokenSequences.length; i++) { - if (maxSize < expectedTokenSequences[i].length) - maxSize = expectedTokenSequences[i].length; - for (int j = 0; j < expectedTokenSequences[i].length; j++) - expected.append(tokenImage[expectedTokenSequences[i][j]]).append(' '); - - if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) - expected.append("..."); - expected.append(EOL).append(" "); - } - - StringBuilder sb = new StringBuilder(); - sb.append ("Encountered \""); - - Token tok = currentToken.next; - for (int i = 0; i < maxSize; i++) { - String tokenText = tok.image; - String escapedTokenText = add_escapes(tokenText); - if (i != 0) - sb.append (' '); - if (tok.kind == 0) { - sb.append(tokenImage[0]); - break; - } - sb.append(" " + tokenImage[tok.kind]); - sb.append(" \""); - sb.append(escapedTokenText); - sb.append("\""); - tok = tok.next; - } - sb.append ("\" at line ") - .append (currentToken.next.beginLine) - .append (", column ") - .append (currentToken.next.beginColumn); - sb.append(".").append(EOL); - - if (expectedTokenSequences.length == 0) { - // Nothing to add here - } else { - sb.append (EOL) - .append ("Was expecting") - .append (expectedTokenSequences.length == 1 ? ":" : " one of:") - .append (EOL) - .append (EOL) - .append (expected); - } - - return sb.toString (); - } - - - /** - * Used to convert raw characters to their escaped version - * when these raw version cannot be used as part of an ASCII - * string literal. - */ - static String add_escapes(String str) { - final StringBuilder retval = new StringBuilder(); - for (int i = 0; i < str.length(); i++) { - final char ch = str.charAt(i); - switch (ch) - { - case '\b': - retval.append("\\b"); - continue; - case '\t': - retval.append("\\t"); - continue; - case '\n': - retval.append("\\n"); - continue; - case '\f': - retval.append("\\f"); - continue; - case '\r': - retval.append("\\r"); - continue; - case '\"': - retval.append("\\\""); - continue; - case '\'': - retval.append("\\\'"); - continue; - case '\\': - retval.append("\\\\"); - continue; - default: - if (ch < 0x20 || ch > 0x7e) { - String s = "0000" + Integer.toString(ch, 16); - retval.append("\\u").append (s.substring(s.length() - 4, s.length())); - } else { - retval.append(ch); - } - continue; - } - } - return retval.toString(); - } -} -/* ParserGeneratorCC - OriginalChecksum=3bbe87c678f18e50b99252d306f09181 (do not edit this line) */ --- a/src/com/kitfox/svg/animation/parser/SimpleCharStream.java +++ /dev/null @@ -1,197 +0,0 @@ -/* Generated by: ParserGeneratorCC: Do not edit this line. SimpleCharStream.java Version 1.1 */ -/* ParserGeneratorCCOptions:SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ -package com.kitfox.svg.animation.parser; - -/** - * An implementation of interface CharStream, where the stream is assumed to - * contain only ASCII characters (without unicode processing). - */ -public -class SimpleCharStream extends AbstractCharStream -{ - protected java.io.Reader inputStream; - - @Override - protected int streamRead(final char[] buffer, final int offset, final int len) throws java.io.IOException { - return inputStream.read (buffer, offset, len); - } - - @Override - protected void streamClose() throws java.io.IOException { - inputStream.close (); - } - - protected void fillBuff() throws java.io.IOException - { - if (maxNextCharInd == available) - { - if (available == bufsize) - { - if (tokenBegin > 2048) - { - maxNextCharInd = 0; - bufpos = 0; - available = tokenBegin; - } - else - if (tokenBegin < 0) { - maxNextCharInd = 0; - bufpos = 0; - } - else - expandBuff(false); - } - else - if (available > tokenBegin) - available = bufsize; - else - if ((tokenBegin - available) < 2048) - expandBuff(true); - else - available = tokenBegin; - } - - try { - final int i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd); - if (i == -1) - { - inputStream.close(); - throw new java.io.IOException(); - } - maxNextCharInd += i; - return; - } - catch(java.io.IOException e) { - --bufpos; - backup(0); - if (tokenBegin == -1) - tokenBegin = bufpos; - throw e; - } - } - - /** Read a character. */ - public char readChar() throws java.io.IOException - { - if (inBuf > 0) - { - --inBuf; - - if (++bufpos == bufsize) - bufpos = 0; - - return buffer[bufpos]; - } - - ++bufpos; - if (bufpos >= maxNextCharInd) - fillBuff(); - - char c = buffer[bufpos]; - - if (isTrackLineColumn()) - updateLineColumn(c); - return c; - } - - /** Constructor. */ - public SimpleCharStream(final java.io.Reader dstream, - final int startline, - final int startcolumn, - final int buffersize) - { - super (startline, startcolumn, buffersize); - inputStream = dstream; - } - - /** Constructor. */ - public SimpleCharStream(final java.io.Reader dstream, - final int startline, - final int startcolumn) - { - this(dstream, startline, startcolumn, 4096); - } - - /** Constructor. */ - public SimpleCharStream(final java.io.Reader dstream) - { - this(dstream, 1, 1, 4096); - } - - /** Reinitialise. */ - public void reInit(final java.io.Reader dstream) - { - reInit(dstream, 1, 1, 4096); - } - - /** Reinitialise. */ - public void reInit(final java.io.Reader dstream, - final int startline, - final int startcolumn) - { - reInit(dstream, startline, startcolumn, 4096); - } - - /** Reinitialise. */ - public void reInit(final java.io.Reader dstream, - final int startline, - final int startcolumn, - final int buffersize) - { - inputStream = dstream; - super.reInit (startline, startcolumn, buffersize); - } - - /** Constructor. */ - public SimpleCharStream(final java.io.InputStream dstream, - final java.nio.charset.Charset encoding, - final int startline, - final int startcolumn, - final int buffersize) - { - this(new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize); - } - - /** Constructor. */ - public SimpleCharStream(final java.io.InputStream dstream, - final java.nio.charset.Charset encoding, - final int startline, - final int startcolumn) - { - this(dstream, encoding, startline, startcolumn, 4096); - } - - /** Constructor. */ - public SimpleCharStream(final java.io.InputStream dstream, - final java.nio.charset.Charset encoding) - { - this(dstream, encoding, 1, 1, 4096); - } - - /** Reinitialise. */ - public void reInit(final java.io.InputStream dstream, - final java.nio.charset.Charset encoding) - { - reInit(dstream, encoding, 1, 1, 4096); - } - - /** Reinitialise. */ - public void reInit(final java.io.InputStream dstream, - final java.nio.charset.Charset encoding, - final int startline, - final int startcolumn) - { - reInit(dstream, encoding, startline, startcolumn, 4096); - } - - /** Reinitialise. */ - public void reInit(final java.io.InputStream dstream, - final java.nio.charset.Charset encoding, - final int startline, - final int startcolumn, - final int buffersize) - { - reInit(new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize); - } -} -/* ParserGeneratorCC - OriginalChecksum=5b53f2d1fc73cc5d8e04831a0ba6a339 (do not edit this line) */ --- a/src/com/kitfox/svg/animation/parser/SimpleNode.java +++ /dev/null @@ -1,91 +0,0 @@ -/* Generated by: JJTree: Do not edit this line. SimpleNode.java Version 1.1 */ -/* ParserGeneratorCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=false,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ -package com.kitfox.svg.animation.parser; - -public -class SimpleNode - implements Node { - protected Node parent; - protected Node[] children; - protected int id; - protected Object value; - protected AnimTimeParser parser; - - public SimpleNode(final int i) { - id = i; - } - - public SimpleNode(final AnimTimeParser p, final int i) { - this(i); - parser = p; - } - - public void jjtOpen() { - } - - public void jjtClose() { - } - - public void jjtSetParent(final Node n) { parent = n; } - public Node jjtGetParent() { return parent; } - - public void jjtAddChild(final Node n, final int i) { - if (children == null) { - children = new Node[i + 1]; - } else if (i >= children.length) { - Node c[] = new Node[i + 1]; - System.arraycopy(children, 0, c, 0, children.length); - children = c; - } - children[i] = n; - } - - public Node jjtGetChild(final int i) { - return children[i]; - } - - public int jjtGetNumChildren() { - return children == null ? 0 : children.length; - } - - public void jjtSetValue(final Object aValue) { value = aValue; } - public Object jjtGetValue() { return value; } - - /* You can override these two methods in subclasses of SimpleNode to - customize the way the node appears when the tree is dumped. If - your output uses more than one line you should override - toString(String), otherwise overriding toString() is probably all - you need to do. */ - @Override - public String toString() { - return AnimTimeParserTreeConstants.jjtNodeName[id]; - } - - public String toString(String prefix) { - return prefix + toString(); - } - - protected void dumpString (String s) { - // TODO get rid of this - System.out.println (s); - } - - /* Override this method if you want to customize how the node dumps - out its children. */ - public void dump(String prefix) { - dumpString(toString(prefix)); - if (children != null) { - for (int i = 0; i < children.length; ++i) { - SimpleNode n = (SimpleNode)children[i]; - if (n != null) - n.dump(prefix + " "); - } - } - } - - public int getId() { - return id; - } -} - -/* ParserGeneratorCC - OriginalChecksum=9db447086ea72a0895d3c4d6b3b76fa1 (do not edit this line) */ --- a/src/com/kitfox/svg/animation/parser/Token.java +++ /dev/null @@ -1,132 +0,0 @@ -/* Generated by: ParserGeneratorCC: Do not edit this line. Token.java Version 1.1 */ -/* ParserGeneratorCCOptions:TOKEN_EXTENDS=,KEEP_LINE_COLUMN=true,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ -package com.kitfox.svg.animation.parser; - -/** - * Describes the input token stream. - */ - -public class Token -implements java.io.Serializable { - /** - * The version identifier for this Serializable class. - * Increment only if the serialized form of the - * class changes. - */ - private static final long serialVersionUID = 1L; - - /** - * An integer that describes the kind of this token. This numbering - * system is determined by JavaCCParser, and a table of these numbers is - * stored in the file ...Constants.java. - */ - public int kind; - - /** The line number of the first character of this Token. */ - public int beginLine; - /** The column number of the first character of this Token. */ - public int beginColumn; - /** The line number of the last character of this Token. */ - public int endLine; - /** The column number of the last character of this Token. */ - public int endColumn; - - /** - * The string image of the token. - */ - public String image; - - /** - * A reference to the next regular (non-special) token from the input - * stream. If this is the last token from the input stream, or if the - * token manager has not read tokens beyond this one, this field is - * set to null. This is true only if this token is also a regular - * token. Otherwise, see below for a description of the contents of - * this field. - */ - public Token next; - - /** - * This field is used to access special tokens that occur prior to this - * token, but after the immediately preceding regular (non-special) token. - * If there are no such special tokens, this field is set to null. - * When there are more than one such special token, this field refers - * to the last of these special tokens, which in turn refers to the next - * previous special token through its specialToken field, and so on - * until the first special token (whose specialToken field is null). - * The next fields of special tokens refer to other special tokens that - * immediately follow it (without an intervening regular token). If there - * is no such token, this field is null. - */ - public Token specialToken; - - /** - * No-argument constructor - */ - public Token() {} - - /** - * Constructs a new token for the specified Image. - */ - public Token(final int nKind) - { - this(nKind, null); - } - - /** - * Constructs a new token for the specified Image and Kind. - */ - public Token(final int nKind, final String sImage) - { - this.kind = nKind; - this.image = sImage; - } - - /** - * An optional attribute value of the Token. - * Tokens which are not used as syntactic sugar will often contain - * meaningful values that will be used later on by the compiler or - * interpreter. This attribute value is often different from the image. - * Any subclass of Token that actually wants to return a non-null value can - * override this method as appropriate. - */ - public Object getValue() { - return null; - } - - /** - * Returns the image. - */ - @Override - public String toString() - { - return image; - } - - /** - * Returns a new Token object, by default. However, if you want, you - * can create and return subclass objects based on the value of ofKind. - * Simply add the cases to the switch for all those special cases. - * For example, if you have a subclass of Token called IDToken that - * you want to create if ofKind is ID, simply add something like : - * - * case MyParserConstants.ID : return new IDToken(ofKind, image); - * - * to the following switch statement. Then you can cast matchedToken - * variable to the appropriate type and use sit in your lexical actions. - */ - public static Token newToken(int ofKind, String image) - { - switch(ofKind) - { - default : return new Token(ofKind, image); - } - } - - public static Token newToken(int ofKind) - { - return newToken(ofKind, null); - } - -} -/* ParserGeneratorCC - OriginalChecksum=e59213b685f13f069956e501c4cb9348 (do not edit this line) */ --- a/src/com/kitfox/svg/animation/parser/TokenMgrException.java +++ /dev/null @@ -1,146 +0,0 @@ -/* Generated by: ParserGeneratorCC: Do not edit this line. TokenMgrException.java Version 1.1 */ -/* ParserGeneratorCCOptions: */ -package com.kitfox.svg.animation.parser; - -/** Token Manager Error. */ -public class TokenMgrException extends RuntimeException -{ - - /** - * The version identifier for this Serializable class. - * Increment only if the serialized form of the - * class changes. - */ - private static final long serialVersionUID = 1L; - - /* - * Ordinals for various reasons why an Error of this type can be thrown. - */ - - /** - * Lexical error occurred. - */ - public static final int LEXICAL_ERROR = 0; - - /** - * An attempt was made to create a second instance of a static token manager. - */ - public static final int STATIC_LEXER_ERROR = 1; - - /** - * Tried to change to an invalid lexical state. - */ - public static final int INVALID_LEXICAL_STATE = 2; - - /** - * Detected (and bailed out of) an infinite loop in the token manager. - */ - public static final int LOOP_DETECTED = 3; - - /** - * Indicates the reason why the exception is thrown. It will have - * one of the above 4 values. - */ - int errorCode; - - /** - * Replaces unprintable characters by their escaped (or unicode escaped) - * equivalents in the given string - */ - protected static final String addEscapes(String str) { - StringBuilder retval = new StringBuilder(); - for (int i = 0; i < str.length(); i++) { - final char ch = str.charAt(i); - switch (ch) - { - case '\b': - retval.append("\\b"); - continue; - case '\t': - retval.append("\\t"); - continue; - case '\n': - retval.append("\\n"); - continue; - case '\f': - retval.append("\\f"); - continue; - case '\r': - retval.append("\\r"); - continue; - case '\"': - retval.append("\\\""); - continue; - case '\'': - retval.append("\\\'"); - continue; - case '\\': - retval.append("\\\\"); - continue; - default: - if (ch < 0x20 || ch > 0x7e) { - String s = "0000" + Integer.toString(ch, 16); - retval.append("\\u").append (s.substring(s.length() - 4, s.length())); - } else { - retval.append(ch); - } - continue; - } - } - return retval.toString(); - } - - /** - * Returns a detailed message for the Error when it is thrown by the - * token manager to indicate a lexical error. - * Parameters : - * EOFSeen : indicates if EOF caused the lexical error - * curLexState : lexical state in which this error occurred - * errorLine : line number when the error occurred - * errorColumn : column number when the error occurred - * errorAfter : prefix that was seen before this error occurred - * curchar : the offending character - * Note: You can customize the lexical error message by modifying this method. - */ - protected static String LexicalErr(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, int curChar) { - char curChar1 = (char)curChar; - return("Lexical error at line " + - errorLine + ", column " + - errorColumn + ". Encountered: " + - (EOFSeen ? " " : ("\"" + addEscapes(String.valueOf(curChar1)) + "\"") + " (" + curChar + "), ") + - "after : \"" + addEscapes(errorAfter) + "\""); - } - - /** - * You can also modify the body of this method to customize your error messages. - * For example, cases like LOOP_DETECTED and INVALID_LEXICAL_STATE are not - * of end-users concern, so you can return something like : - * - * "Internal Error : Please file a bug report .... " - * - * from this method for such cases in the release version of your parser. - */ - @Override - public String getMessage() { - return super.getMessage(); - } - - /* - * Constructors of various flavors follow. - */ - /** No arg constructor. */ - public TokenMgrException() { - } - - /** Constructor with message and reason. */ - public TokenMgrException(String message, int reason) { - super(message); - errorCode = reason; - } - - /** Full Constructor. */ - public TokenMgrException(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, int curChar, int reason) { - this(LexicalErr(EOFSeen, lexState, errorLine, errorColumn, errorAfter, curChar), reason); - } -} -/* ParserGeneratorCC - OriginalChecksum=a7dcf3b91bbde73a946148690ebd07be (do not edit this line) */ --- a/src/com/kitfox/svg/app/MainFrame.form +++ /dev/null @@ -1,76 +0,0 @@ - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --- a/src/com/kitfox/svg/app/MainFrame.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on September 6, 2004, 1:19 AM - */ - -package com.kitfox.svg.app; - -/** - * - * @author kitfox - */ -public class MainFrame extends javax.swing.JFrame -{ - public static final long serialVersionUID = 1; - - /** Creates new form MainFrame */ - public MainFrame() - { - initComponents(); - } - - /** This method is called from within the constructor to - * initialize the form. - * WARNING: Do NOT modify this code. The content of this method is - * always regenerated by the Form Editor. - */ - private void initComponents()//GEN-BEGIN:initComponents - { - jPanel1 = new javax.swing.JPanel(); - bn_svgViewer = new javax.swing.JButton(); - bn_svgViewer1 = new javax.swing.JButton(); - jPanel2 = new javax.swing.JPanel(); - bn_quit = new javax.swing.JButton(); - - setTitle("SVG Salamander - Application Launcher"); - addWindowListener(new java.awt.event.WindowAdapter() - { - @Override - public void windowClosing(java.awt.event.WindowEvent evt) - { - exitForm(evt); - } - }); - - jPanel1.setLayout(new javax.swing.BoxLayout(jPanel1, javax.swing.BoxLayout.Y_AXIS)); - - bn_svgViewer.setText("SVG Viewer (No animation)"); - bn_svgViewer.addActionListener(new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent evt) - { - bn_svgViewerActionPerformed(evt); - } - }); - - jPanel1.add(bn_svgViewer); - - bn_svgViewer1.setText("SVG Player (Animation)"); - bn_svgViewer1.addActionListener(new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent evt) - { - bn_svgViewer1ActionPerformed(evt); - } - }); - - jPanel1.add(bn_svgViewer1); - - getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER); - - bn_quit.setText("Quit"); - bn_quit.addActionListener(new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent evt) - { - bn_quitActionPerformed(evt); - } - }); - - jPanel2.add(bn_quit); - - getContentPane().add(jPanel2, java.awt.BorderLayout.SOUTH); - - pack(); - }//GEN-END:initComponents - - private void bn_svgViewer1ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_bn_svgViewer1ActionPerformed - {//GEN-HEADEREND:event_bn_svgViewer1ActionPerformed - SVGPlayer.main(null); - - close(); - }//GEN-LAST:event_bn_svgViewer1ActionPerformed - - private void bn_svgViewerActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_bn_svgViewerActionPerformed - {//GEN-HEADEREND:event_bn_svgViewerActionPerformed - SVGViewer.main(null); - - close(); - }//GEN-LAST:event_bn_svgViewerActionPerformed - - private void bn_quitActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_bn_quitActionPerformed - {//GEN-HEADEREND:event_bn_quitActionPerformed - exitForm(null); - }//GEN-LAST:event_bn_quitActionPerformed - - /** Exit the Application */ - private void exitForm(java.awt.event.WindowEvent evt)//GEN-FIRST:event_exitForm - { - System.exit(0); - }//GEN-LAST:event_exitForm - - private void close() - { - this.setVisible(false); - this.dispose(); - } - - /** - * @param args the command line arguments - */ - public static void main(String args[]) - { - new MainFrame().setVisible(true); - } - - // Variables declaration - do not modify//GEN-BEGIN:variables - private javax.swing.JButton bn_quit; - private javax.swing.JButton bn_svgViewer; - private javax.swing.JButton bn_svgViewer1; - private javax.swing.JPanel jPanel1; - private javax.swing.JPanel jPanel2; - // End of variables declaration//GEN-END:variables - -} --- a/src/com/kitfox/svg/app/PlayerDialog.form +++ /dev/null @@ -1,137 +0,0 @@ - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --- a/src/com/kitfox/svg/app/PlayerDialog.java +++ /dev/null @@ -1,301 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on September 28, 2004, 9:56 PM - */ - -package com.kitfox.svg.app; - -/** - * - * @author kitfox - */ -public class PlayerDialog extends javax.swing.JDialog implements PlayerThreadListener -{ - public static final long serialVersionUID = 1; - - PlayerThread thread; - - final SVGPlayer parent; - - /** Creates new form PlayerDialog */ - public PlayerDialog(SVGPlayer parent) - { - super(parent, false); - initComponents(); - - this.parent = parent; - - thread = new PlayerThread(); - thread.addListener(this); - - text_timeStepActionPerformed(null); - } - - public void updateTime(double curTime, double timeStep, int playState) - { - if (playState == PlayerThread.PS_STOP) return; - - text_curTime.setText("" + (float)curTime); - parent.updateTime(curTime); -// text_timeStep.setText("" + (int)(1.0 / timeStep)); - } - - /** This method is called from within the constructor to - * initialize the form. - * WARNING: Do NOT modify this code. The content of this method is - * always regenerated by the Form Editor. - */ - // //GEN-BEGIN:initComponents - private void initComponents() - { - jPanel1 = new javax.swing.JPanel(); - bn_playBack = new javax.swing.JButton(); - bn_stop = new javax.swing.JButton(); - bn_playFwd = new javax.swing.JButton(); - jPanel2 = new javax.swing.JPanel(); - jPanel3 = new javax.swing.JPanel(); - jLabel1 = new javax.swing.JLabel(); - text_curTime = new javax.swing.JTextField(); - bn_time0 = new javax.swing.JButton(); - jPanel4 = new javax.swing.JPanel(); - jLabel2 = new javax.swing.JLabel(); - text_timeStep = new javax.swing.JTextField(); - - setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); - setTitle("Player"); - addWindowListener(new java.awt.event.WindowAdapter() - { - @Override - public void windowClosed(java.awt.event.WindowEvent evt) - { - formWindowClosed(evt); - } - }); - - bn_playBack.setText("<"); - bn_playBack.setToolTipText("Play backwards"); - bn_playBack.addActionListener(new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent evt) - { - bn_playBackActionPerformed(evt); - } - }); - - jPanel1.add(bn_playBack); - - bn_stop.setText("||"); - bn_stop.setToolTipText("Stop playback"); - bn_stop.addActionListener(new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent evt) - { - bn_stopActionPerformed(evt); - } - }); - - jPanel1.add(bn_stop); - - bn_playFwd.setText(">"); - bn_playFwd.setToolTipText("Play Forwards"); - bn_playFwd.addActionListener(new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent evt) - { - bn_playFwdActionPerformed(evt); - } - }); - - jPanel1.add(bn_playFwd); - - getContentPane().add(jPanel1, java.awt.BorderLayout.NORTH); - - jPanel2.setLayout(new javax.swing.BoxLayout(jPanel2, javax.swing.BoxLayout.Y_AXIS)); - - jLabel1.setText("Cur Time"); - jPanel3.add(jLabel1); - - text_curTime.setHorizontalAlignment(javax.swing.JTextField.LEFT); - text_curTime.setText("0"); - text_curTime.setPreferredSize(new java.awt.Dimension(100, 21)); - text_curTime.addActionListener(new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent evt) - { - text_curTimeActionPerformed(evt); - } - }); - text_curTime.addFocusListener(new java.awt.event.FocusAdapter() - { - @Override - public void focusLost(java.awt.event.FocusEvent evt) - { - text_curTimeFocusLost(evt); - } - }); - - jPanel3.add(text_curTime); - - bn_time0.setText("Time 0"); - bn_time0.setToolTipText("Reset time to first frame"); - bn_time0.addActionListener(new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent evt) - { - bn_time0ActionPerformed(evt); - } - }); - - jPanel3.add(bn_time0); - - jPanel2.add(jPanel3); - - jLabel2.setText("Frames Per Second"); - jPanel4.add(jLabel2); - - text_timeStep.setHorizontalAlignment(javax.swing.JTextField.RIGHT); - text_timeStep.setText("60"); - text_timeStep.setPreferredSize(new java.awt.Dimension(100, 21)); - text_timeStep.addActionListener(new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent evt) - { - text_timeStepActionPerformed(evt); - } - }); - text_timeStep.addFocusListener(new java.awt.event.FocusAdapter() - { - @Override - public void focusLost(java.awt.event.FocusEvent evt) - { - text_timeStepFocusLost(evt); - } - }); - - jPanel4.add(text_timeStep); - - jPanel2.add(jPanel4); - - getContentPane().add(jPanel2, java.awt.BorderLayout.CENTER); - - pack(); - }// //GEN-END:initComponents - - private void bn_time0ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_bn_time0ActionPerformed - {//GEN-HEADEREND:event_bn_time0ActionPerformed - thread.setCurTime(0); - }//GEN-LAST:event_bn_time0ActionPerformed - - private void bn_playFwdActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_bn_playFwdActionPerformed - {//GEN-HEADEREND:event_bn_playFwdActionPerformed - thread.setPlayState(PlayerThread.PS_PLAY_FWD); - }//GEN-LAST:event_bn_playFwdActionPerformed - - private void bn_stopActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_bn_stopActionPerformed - {//GEN-HEADEREND:event_bn_stopActionPerformed - thread.setPlayState(PlayerThread.PS_STOP); - }//GEN-LAST:event_bn_stopActionPerformed - - private void bn_playBackActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_bn_playBackActionPerformed - {//GEN-HEADEREND:event_bn_playBackActionPerformed - thread.setPlayState(PlayerThread.PS_PLAY_BACK); - }//GEN-LAST:event_bn_playBackActionPerformed - - private void formWindowClosed(java.awt.event.WindowEvent evt)//GEN-FIRST:event_formWindowClosed - {//GEN-HEADEREND:event_formWindowClosed -// thread.exit(); - }//GEN-LAST:event_formWindowClosed - - private void text_timeStepFocusLost(java.awt.event.FocusEvent evt)//GEN-FIRST:event_text_timeStepFocusLost - {//GEN-HEADEREND:event_text_timeStepFocusLost - text_timeStepActionPerformed(null); - }//GEN-LAST:event_text_timeStepFocusLost - - private void text_timeStepActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_text_timeStepActionPerformed - {//GEN-HEADEREND:event_text_timeStepActionPerformed - try - { - int val = Integer.parseInt(text_timeStep.getText()); - thread.setTimeStep(1.0 / val); - } - catch (Exception e) - { - } - - double d = thread.getTimeStep(); - String newStrn = "" + (int)(1f / d); - if (newStrn.equals(text_timeStep.getText())) return; - text_timeStep.setText(newStrn); - -// text_timeStepActionPerformed(null); - }//GEN-LAST:event_text_timeStepActionPerformed - - private void text_curTimeActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_text_curTimeActionPerformed - {//GEN-HEADEREND:event_text_curTimeActionPerformed - try - { - double val = Double.parseDouble(text_curTime.getText()); - thread.setCurTime(val); - } - catch (Exception e) - { - } - - double d = thread.getCurTime(); - text_curTime.setText("" + (float)d); - - text_timeStepActionPerformed(null); - }//GEN-LAST:event_text_curTimeActionPerformed - - private void text_curTimeFocusLost(java.awt.event.FocusEvent evt)//GEN-FIRST:event_text_curTimeFocusLost - {//GEN-HEADEREND:event_text_curTimeFocusLost - text_curTimeActionPerformed(null); - }//GEN-LAST:event_text_curTimeFocusLost - - // Variables declaration - do not modify//GEN-BEGIN:variables - private javax.swing.JButton bn_playBack; - private javax.swing.JButton bn_playFwd; - private javax.swing.JButton bn_stop; - private javax.swing.JButton bn_time0; - private javax.swing.JLabel jLabel1; - private javax.swing.JLabel jLabel2; - private javax.swing.JPanel jPanel1; - private javax.swing.JPanel jPanel2; - private javax.swing.JPanel jPanel3; - private javax.swing.JPanel jPanel4; - private javax.swing.JTextField text_curTime; - private javax.swing.JTextField text_timeStep; - // End of variables declaration//GEN-END:variables - -} --- a/src/com/kitfox/svg/app/PlayerThread.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on September 28, 2004, 10:07 PM - */ - - -package com.kitfox.svg.app; - -import java.util.*; - -/** - * - * @author kitfox - */ -public class PlayerThread implements Runnable -{ - HashSet listeners = new HashSet(); - - double curTime = 0; - double timeStep = .2; - - public static final int PS_STOP = 0; - public static final int PS_PLAY_FWD = 1; - public static final int PS_PLAY_BACK = 2; - - int playState = PS_STOP; - - Thread thread; - - /** Creates a new instance of PlayerThread */ - public PlayerThread() - { - thread = new Thread(this); - thread.start(); - } - - public void run() - { - while (thread != null) - { - synchronized (this) - { - switch (playState) - { - case PS_PLAY_FWD: - curTime += timeStep; - break; - case PS_PLAY_BACK: - curTime -= timeStep; - if (curTime < 0) curTime = 0; - break; - default: - case PS_STOP: - break; - } - - fireTimeUpdateEvent(); - } - - try - { - Thread.sleep((long)(timeStep * 1000)); - } - catch (Exception e) - { - throw new RuntimeException(e); - } - } - } - - public void exit() { thread = null; } - public synchronized void addListener(PlayerThreadListener listener) - { - listeners.add(listener); - } - - public synchronized double getCurTime() { return curTime; } - - public synchronized void setCurTime(double time) - { - curTime = time; - } - - public synchronized double getTimeStep() { return timeStep; } - - public synchronized void setTimeStep(double time) - { - timeStep = time; - if (timeStep < .01) timeStep = .01; - } - - public synchronized int getPlayState() { return playState; } - - public synchronized void setPlayState(int playState) - { - this.playState = playState; - } - - private void fireTimeUpdateEvent() - { - for (PlayerThreadListener listener : listeners) { - listener.updateTime(curTime, timeStep, playState); - } - } -} --- a/src/com/kitfox/svg/app/PlayerThreadListener.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on September 28, 2004, 10:15 PM - */ - -package com.kitfox.svg.app; - -/** - * - * @author kitfox - */ -public interface PlayerThreadListener -{ - public void updateTime(double curTime, double timeStep, int playState); -} --- a/src/com/kitfox/svg/app/SVGPlayer.form +++ /dev/null @@ -1,122 +0,0 @@ - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --- a/src/com/kitfox/svg/app/SVGPlayer.java +++ /dev/null @@ -1,451 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on April 3, 2004, 5:28 PM - */ - -package com.kitfox.svg.app; - - -import com.kitfox.svg.SVGConst; -import com.kitfox.svg.SVGDiagram; -import com.kitfox.svg.SVGDisplayPanel; -import com.kitfox.svg.SVGElement; -import com.kitfox.svg.SVGException; -import com.kitfox.svg.SVGUniverse; -import java.awt.Color; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.geom.Point2D; -import java.io.File; -import java.io.InputStream; -import java.net.URI; -import java.net.URL; -import java.net.URLEncoder; -import java.security.AccessControlException; -import java.util.ArrayList; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import javax.swing.JFileChooser; -import javax.swing.JOptionPane; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class SVGPlayer extends javax.swing.JFrame -{ - public static final long serialVersionUID = 1; - - SVGDisplayPanel svgDisplayPanel = new SVGDisplayPanel(); - - final PlayerDialog playerDialog; - - SVGUniverse universe; - - /** FileChooser for running in trusted environments */ - final JFileChooser fileChooser; - { -// fileChooser = new JFileChooser(new File(".")); - JFileChooser fc = null; - try - { - fc = new JFileChooser(); - fc.setFileFilter( - new javax.swing.filechooser.FileFilter() { - final Matcher matchLevelFile = Pattern.compile(".*\\.svg[z]?").matcher(""); - - @Override - public boolean accept(File file) - { - if (file.isDirectory()) return true; - - matchLevelFile.reset(file.getName()); - return matchLevelFile.matches(); - } - - @Override - public String getDescription() { return "SVG file (*.svg, *.svgz)"; } - } - ); - } - catch (AccessControlException ex) - { - //Do not create file chooser if webstart refuses permissions - } - fileChooser = fc; - } - - /** Backup file service for opening files in WebStart situations */ - /* - final FileOpenService fileOpenService; - { - try - { - fileOpenService = (FileOpenService)ServiceManager.lookup("javax.jnlp.FileOpenService"); - } - catch (UnavailableServiceException e) - { - fileOpenService = null; - } - } - */ - - /** Creates new form SVGViewer */ - public SVGPlayer() { - initComponents(); - - setSize(800, 600); - - svgDisplayPanel.setBgColor(Color.white); - svgDisplayPanel.addMouseListener(new MouseAdapter() - { - @Override - public void mouseClicked(MouseEvent evt) - { - SVGDiagram diagram = svgDisplayPanel.getDiagram(); - if (diagram == null) return; - - System.out.println("Picking at cursor (" + evt.getX() + ", " + evt.getY() + ")"); - try - { - List> paths = diagram.pick(new Point2D.Float(evt.getX(), evt.getY()), null); - for (int i = 0; i < paths.size(); i++) - { - System.out.println(pathToString(paths.get(i))); - } - } - catch (SVGException ex) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, - "Could not pick", ex); - } - } - } - ); - - svgDisplayPanel.setPreferredSize(getSize()); - scrollPane_svgArea.setViewportView(svgDisplayPanel); - - playerDialog = new PlayerDialog(this); - } - - private String pathToString(List path) - { - if (path.size() == 0) return ""; - - StringBuffer sb = new StringBuffer(); - sb.append(path.get(0)); - for (int i = 1; i < path.size(); i++) - { - sb.append("/"); - sb.append(path.get(i).getId()); - } - return sb.toString(); - } - - public void updateTime(double curTime) - { - try - { - if (universe != null) - { - universe.setCurTime(curTime); - universe.updateTime(); - // svgDisplayPanel.updateTime(curTime); - repaint(); - } - } - catch (Exception e) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, null, e); - } - } - - private void loadURL(URL url) - { - boolean verbose = cmCheck_verbose.isSelected(); - - universe = new SVGUniverse(); - universe.setVerbose(verbose); - SVGDiagram diagram = null; - - if (!CheckBoxMenuItem_anonInputStream.isSelected()) - { - //Load from a disk with a valid URL - URI uri = universe.loadSVG(url); - - if (verbose) System.err.println(uri.toString()); - - diagram = universe.getDiagram(uri); - } - else - { - //Load from a stream with no particular valid URL - try - { - InputStream is = url.openStream(); - URI uri = universe.loadSVG(is, "defaultName"); - - if (verbose) System.err.println(uri.toString()); - - diagram = universe.getDiagram(uri); - } - catch (Exception e) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, null, e); - } - } - - svgDisplayPanel.setDiagram(diagram); - repaint(); - } - - /** This method is called from within the constructor to - * initialize the form. - * WARNING: Do NOT modify this code. The content of this method is - * always regenerated by the Form Editor. - */ - // //GEN-BEGIN:initComponents - private void initComponents() - { - scrollPane_svgArea = new javax.swing.JScrollPane(); - jMenuBar1 = new javax.swing.JMenuBar(); - menu_file = new javax.swing.JMenu(); - cm_loadFile = new javax.swing.JMenuItem(); - cm_loadUrl = new javax.swing.JMenuItem(); - menu_window = new javax.swing.JMenu(); - cm_player = new javax.swing.JMenuItem(); - jSeparator2 = new javax.swing.JSeparator(); - cm_800x600 = new javax.swing.JMenuItem(); - CheckBoxMenuItem_anonInputStream = new javax.swing.JCheckBoxMenuItem(); - cmCheck_verbose = new javax.swing.JCheckBoxMenuItem(); - menu_help = new javax.swing.JMenu(); - cm_about = new javax.swing.JMenuItem(); - - setTitle("SVG Player - Salamander Project"); - addWindowListener(new java.awt.event.WindowAdapter() - { - @Override - public void windowClosing(java.awt.event.WindowEvent evt) - { - exitForm(evt); - } - }); - - getContentPane().add(scrollPane_svgArea, java.awt.BorderLayout.CENTER); - - menu_file.setMnemonic('f'); - menu_file.setText("File"); - cm_loadFile.setMnemonic('l'); - cm_loadFile.setText("Load File..."); - cm_loadFile.addActionListener(new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent evt) - { - cm_loadFileActionPerformed(evt); - } - }); - - menu_file.add(cm_loadFile); - - cm_loadUrl.setText("Load URL..."); - cm_loadUrl.addActionListener(new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent evt) - { - cm_loadUrlActionPerformed(evt); - } - }); - - menu_file.add(cm_loadUrl); - - jMenuBar1.add(menu_file); - - menu_window.setText("Window"); - cm_player.setText("Player"); - cm_player.addActionListener(new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent evt) - { - cm_playerActionPerformed(evt); - } - }); - - menu_window.add(cm_player); - - menu_window.add(jSeparator2); - - cm_800x600.setText("800 x 600"); - cm_800x600.addActionListener(new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent evt) - { - cm_800x600ActionPerformed(evt); - } - }); - - menu_window.add(cm_800x600); - - CheckBoxMenuItem_anonInputStream.setText("Anonymous Input Stream"); - menu_window.add(CheckBoxMenuItem_anonInputStream); - - cmCheck_verbose.setText("Verbose"); - cmCheck_verbose.addActionListener(new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent evt) - { - cmCheck_verboseActionPerformed(evt); - } - }); - - menu_window.add(cmCheck_verbose); - - jMenuBar1.add(menu_window); - - menu_help.setText("Help"); - cm_about.setText("About..."); - cm_about.addActionListener(new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent evt) - { - cm_aboutActionPerformed(evt); - } - }); - - menu_help.add(cm_about); - - jMenuBar1.add(menu_help); - - setJMenuBar(jMenuBar1); - - pack(); - }// //GEN-END:initComponents - - private void cm_loadUrlActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_cm_loadUrlActionPerformed - {//GEN-HEADEREND:event_cm_loadUrlActionPerformed - String urlStrn = JOptionPane.showInputDialog(this, "Enter URL of SVG file"); - if (urlStrn == null) return; - - try - { - URL url = new URL(URLEncoder.encode(urlStrn, "UTF-8")); - loadURL(url); - } - catch (Exception e) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, null, e); - } - - }//GEN-LAST:event_cm_loadUrlActionPerformed - - private void cmCheck_verboseActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_cmCheck_verboseActionPerformed - {//GEN-HEADEREND:event_cmCheck_verboseActionPerformed -// TODO add your handling code here: - }//GEN-LAST:event_cmCheck_verboseActionPerformed - - private void cm_playerActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_cm_playerActionPerformed - {//GEN-HEADEREND:event_cm_playerActionPerformed - playerDialog.setVisible(true); - }//GEN-LAST:event_cm_playerActionPerformed - - private void cm_aboutActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_cm_aboutActionPerformed - {//GEN-HEADEREND:event_cm_aboutActionPerformed - VersionDialog dia = new VersionDialog(this, true, cmCheck_verbose.isSelected()); - dia.setVisible(true); -// JOptionPane.showMessageDialog(this, "Salamander SVG - Created by Mark McKay\nhttp://www.kitfox.com"); - }//GEN-LAST:event_cm_aboutActionPerformed - - private void cm_800x600ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cm_800x600ActionPerformed - setSize(800, 600); - }//GEN-LAST:event_cm_800x600ActionPerformed - - private void cm_loadFileActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_cm_loadFileActionPerformed - {//GEN-HEADEREND:event_cm_loadFileActionPerformed - boolean verbose = cmCheck_verbose.isSelected(); - - try - { - int retVal = fileChooser.showOpenDialog(this); - if (retVal == JFileChooser.APPROVE_OPTION) - { - File chosenFile = fileChooser.getSelectedFile(); - - URL url = chosenFile.toURI().toURL(); - - loadURL(url); - } - } - catch (Exception e) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, null, e); - } - - }//GEN-LAST:event_cm_loadFileActionPerformed - - /** Exit the Application */ - private void exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm - System.exit(0); - }//GEN-LAST:event_exitForm - - /** - * @param args the command line arguments - */ - public static void main(String args[]) { - new SVGPlayer().setVisible(true); - } - - public void updateTime(double curTime, double timeStep, int playState) - { - } - - // Variables declaration - do not modify//GEN-BEGIN:variables - private javax.swing.JCheckBoxMenuItem CheckBoxMenuItem_anonInputStream; - private javax.swing.JCheckBoxMenuItem cmCheck_verbose; - private javax.swing.JMenuItem cm_800x600; - private javax.swing.JMenuItem cm_about; - private javax.swing.JMenuItem cm_loadFile; - private javax.swing.JMenuItem cm_loadUrl; - private javax.swing.JMenuItem cm_player; - private javax.swing.JMenuBar jMenuBar1; - private javax.swing.JSeparator jSeparator2; - private javax.swing.JMenu menu_file; - private javax.swing.JMenu menu_help; - private javax.swing.JMenu menu_window; - private javax.swing.JScrollPane scrollPane_svgArea; - // End of variables declaration//GEN-END:variables - -} --- a/src/com/kitfox/svg/app/SVGViewer.form +++ /dev/null @@ -1,122 +0,0 @@ - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --- a/src/com/kitfox/svg/app/SVGViewer.java +++ /dev/null @@ -1,426 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on April 3, 2004, 5:28 PM - */ - -package com.kitfox.svg.app; - -import com.kitfox.svg.SVGCache; -import com.kitfox.svg.SVGConst; -import com.kitfox.svg.SVGDiagram; -import com.kitfox.svg.SVGDisplayPanel; -import com.kitfox.svg.SVGElement; -import com.kitfox.svg.SVGException; -import com.kitfox.svg.SVGUniverse; -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Point; -import java.io.File; -import java.io.InputStream; -import java.net.URI; -import java.net.URL; -import java.net.URLEncoder; -import java.security.AccessControlException; -import java.util.ArrayList; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import javax.swing.JFileChooser; -import javax.swing.JOptionPane; - - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class SVGViewer extends javax.swing.JFrame -{ - public static final long serialVersionUID = 1; - - SVGDisplayPanel svgDisplayPanel = new SVGDisplayPanel(); - - /** FileChooser for running in trusted environments */ - final JFileChooser fileChooser; - { -// fileChooser = new JFileChooser(new File(".")); - JFileChooser fc = null; - try - { - fc = new JFileChooser(); - fc.setFileFilter( - new javax.swing.filechooser.FileFilter() { - final Matcher matchLevelFile = Pattern.compile(".*\\.svg[z]?").matcher(""); - - @Override - public boolean accept(File file) - { - if (file.isDirectory()) return true; - - matchLevelFile.reset(file.getName()); - return matchLevelFile.matches(); - } - - @Override - public String getDescription() { return "SVG file (*.svg, *.svgz)"; } - } - ); - } - catch (AccessControlException ex) - { - //Do not create file chooser if webstart refuses permissions - } - fileChooser = fc; - } - - /** Backup file service for opening files in WebStart situations */ - /* - final FileOpenService fileOpenService; - { - try - { - fileOpenService = (FileOpenService)ServiceManager.lookup("javax.jnlp.FileOpenService"); - } - catch (UnavailableServiceException e) - { - fileOpenService = null; - } - } - */ - - /** Creates new form SVGViewer */ - public SVGViewer() { - initComponents(); - - setSize(800, 600); - - svgDisplayPanel.setBgColor(Color.white); - - svgDisplayPanel.setPreferredSize(getSize()); - panel_svgArea.add(svgDisplayPanel, BorderLayout.CENTER); -// scrollPane_svgArea.setViewportView(svgDisplayPanel); - } - - private void loadURL(URL url) - { - boolean verbose = cmCheck_verbose.isSelected(); - -// SVGUniverse universe = new SVGUniverse(); - SVGUniverse universe = SVGCache.getSVGUniverse(); - SVGDiagram diagram = null; - URI uri; - - if (!CheckBoxMenuItem_anonInputStream.isSelected()) - { - //Load from a disk with a valid URL - uri = universe.loadSVG(url); - - if (verbose) System.err.println("Loading document " + uri.toString()); - - diagram = universe.getDiagram(uri); - } - else - { - //Load from a stream with no particular valid URL - try - { - InputStream is = url.openStream(); - uri = universe.loadSVG(is, "defaultName"); - - if (verbose) System.err.println("Loading document " + uri.toString()); - } - catch (Exception e) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, null, e); - return; - } - } -/* -ByteArrayOutputStream bs = new ByteArrayOutputStream(); -ObjectOutputStream os = new ObjectOutputStream(bs); -os.writeObject(universe); -os.close(); - -ByteArrayInputStream bin = new ByteArrayInputStream(bs.toByteArray()); -ObjectInputStream is = new ObjectInputStream(bin); -universe = (SVGUniverse)is.readObject(); -is.close(); -*/ - - diagram = universe.getDiagram(uri); - - svgDisplayPanel.setDiagram(diagram); - repaint(); - } - - /** This method is called from within the constructor to - * initialize the form. - * WARNING: Do NOT modify this code. The content of this method is - * always regenerated by the Form Editor. - */ - // //GEN-BEGIN:initComponents - private void initComponents() - { - scrollPane_svgArea = new javax.swing.JScrollPane(); - panel_svgArea = new javax.swing.JPanel(); - jMenuBar1 = new javax.swing.JMenuBar(); - menu_file = new javax.swing.JMenu(); - cm_loadFile = new javax.swing.JMenuItem(); - cm_loadUrl = new javax.swing.JMenuItem(); - menu_window = new javax.swing.JMenu(); - cm_800x600 = new javax.swing.JMenuItem(); - CheckBoxMenuItem_anonInputStream = new javax.swing.JCheckBoxMenuItem(); - cmCheck_verbose = new javax.swing.JCheckBoxMenuItem(); - menu_help = new javax.swing.JMenu(); - cm_about = new javax.swing.JMenuItem(); - - setTitle("SVG Viewer - Salamander Project"); - addWindowListener(new java.awt.event.WindowAdapter() - { - @Override - public void windowClosing(java.awt.event.WindowEvent evt) - { - exitForm(evt); - } - }); - - panel_svgArea.setLayout(new java.awt.BorderLayout()); - - panel_svgArea.addMouseListener(new java.awt.event.MouseAdapter() - { - @Override - public void mousePressed(java.awt.event.MouseEvent evt) - { - panel_svgAreaMousePressed(evt); - } - @Override - public void mouseReleased(java.awt.event.MouseEvent evt) - { - panel_svgAreaMouseReleased(evt); - } - }); - - scrollPane_svgArea.setViewportView(panel_svgArea); - - getContentPane().add(scrollPane_svgArea, java.awt.BorderLayout.CENTER); - - menu_file.setMnemonic('f'); - menu_file.setText("File"); - cm_loadFile.setMnemonic('l'); - cm_loadFile.setText("Load File..."); - cm_loadFile.addActionListener(new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent evt) - { - cm_loadFileActionPerformed(evt); - } - }); - - menu_file.add(cm_loadFile); - - cm_loadUrl.setText("Load URL..."); - cm_loadUrl.addActionListener(new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent evt) - { - cm_loadUrlActionPerformed(evt); - } - }); - - menu_file.add(cm_loadUrl); - - jMenuBar1.add(menu_file); - - menu_window.setText("Window"); - cm_800x600.setText("800 x 600"); - cm_800x600.addActionListener(new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent evt) - { - cm_800x600ActionPerformed(evt); - } - }); - - menu_window.add(cm_800x600); - - CheckBoxMenuItem_anonInputStream.setText("Anonymous Input Stream"); - menu_window.add(CheckBoxMenuItem_anonInputStream); - - cmCheck_verbose.setText("Verbose"); - cmCheck_verbose.addActionListener(new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent evt) - { - cmCheck_verboseActionPerformed(evt); - } - }); - - menu_window.add(cmCheck_verbose); - - jMenuBar1.add(menu_window); - - menu_help.setText("Help"); - cm_about.setText("About..."); - cm_about.addActionListener(new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent evt) - { - cm_aboutActionPerformed(evt); - } - }); - - menu_help.add(cm_about); - - jMenuBar1.add(menu_help); - - setJMenuBar(jMenuBar1); - - pack(); - }// //GEN-END:initComponents - - private void cm_loadUrlActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_cm_loadUrlActionPerformed - {//GEN-HEADEREND:event_cm_loadUrlActionPerformed - String urlStrn = JOptionPane.showInputDialog(this, "Enter URL of SVG file"); - if (urlStrn == null) return; - - try - { - URL url = new URL(URLEncoder.encode(urlStrn, "UTF-8")); - loadURL(url); - } - catch (Exception e) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, null, e); - } - - }//GEN-LAST:event_cm_loadUrlActionPerformed - - private void panel_svgAreaMouseReleased(java.awt.event.MouseEvent evt)//GEN-FIRST:event_panel_svgAreaMouseReleased - {//GEN-HEADEREND:event_panel_svgAreaMouseReleased - SVGDiagram diagram = svgDisplayPanel.getDiagram(); - List> pickedElements; - try - { - pickedElements = diagram.pick(new Point(evt.getX(), evt.getY()), null); - } - catch (SVGException e) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, null, e); - return; - } - - System.out.println("Pick results:"); - for (List path : pickedElements) { - System.out.print(" Path: "); - - for (SVGElement ele : path) { - System.out.print("" + ele.getId() + "(" + ele.getClass().getName() + ") "); - } - System.out.println(); - } - }//GEN-LAST:event_panel_svgAreaMouseReleased - - private void panel_svgAreaMousePressed(java.awt.event.MouseEvent evt)//GEN-FIRST:event_panel_svgAreaMousePressed - {//GEN-HEADEREND:event_panel_svgAreaMousePressed - - }//GEN-LAST:event_panel_svgAreaMousePressed - - private void cmCheck_verboseActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_cmCheck_verboseActionPerformed - {//GEN-HEADEREND:event_cmCheck_verboseActionPerformed - SVGCache.getSVGUniverse().setVerbose(cmCheck_verbose.isSelected()); - }//GEN-LAST:event_cmCheck_verboseActionPerformed - - private void cm_aboutActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_cm_aboutActionPerformed - {//GEN-HEADEREND:event_cm_aboutActionPerformed - //JOptionPane.showMessageDialog(this, "Salamander SVG - Created by Mark McKay\nhttp://www.kitfox.com"); - VersionDialog dlg = new VersionDialog(this, true, cmCheck_verbose.isSelected()); - dlg.setVisible(true); - }//GEN-LAST:event_cm_aboutActionPerformed - - private void cm_800x600ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cm_800x600ActionPerformed - setSize(800, 600); - }//GEN-LAST:event_cm_800x600ActionPerformed - - private void cm_loadFileActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_cm_loadFileActionPerformed - {//GEN-HEADEREND:event_cm_loadFileActionPerformed - try - { - int retVal = fileChooser.showOpenDialog(this); - if (retVal == JFileChooser.APPROVE_OPTION) - { - File chosenFile = fileChooser.getSelectedFile(); - - URL url = chosenFile.toURI().toURL(); - - loadURL(url); - } - } - catch (Exception e) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, null, e); - } - - }//GEN-LAST:event_cm_loadFileActionPerformed - - /** Exit the Application */ - private void exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm -// setVisible(false); -// dispose(); - System.exit(0); - }//GEN-LAST:event_exitForm - - /** - * @param args the command line arguments - */ - public static void main(String args[]) { - new SVGViewer().setVisible(true); - } - - // Variables declaration - do not modify//GEN-BEGIN:variables - private javax.swing.JCheckBoxMenuItem CheckBoxMenuItem_anonInputStream; - private javax.swing.JCheckBoxMenuItem cmCheck_verbose; - private javax.swing.JMenuItem cm_800x600; - private javax.swing.JMenuItem cm_about; - private javax.swing.JMenuItem cm_loadFile; - private javax.swing.JMenuItem cm_loadUrl; - private javax.swing.JMenuBar jMenuBar1; - private javax.swing.JMenu menu_file; - private javax.swing.JMenu menu_help; - private javax.swing.JMenu menu_window; - private javax.swing.JPanel panel_svgArea; - private javax.swing.JScrollPane scrollPane_svgArea; - // End of variables declaration//GEN-END:variables - -} --- a/src/com/kitfox/svg/app/VersionDialog.form +++ /dev/null @@ -1,69 +0,0 @@ - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --- a/src/com/kitfox/svg/app/VersionDialog.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on January 13, 2005, 7:23 AM - */ - -package com.kitfox.svg.app; - -import com.kitfox.svg.SVGConst; -import java.net.*; -import java.io.*; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * - * @author kitfox - */ -public class VersionDialog extends javax.swing.JDialog -{ - public static final long serialVersionUID = 1; - - final boolean verbose; - - /** Creates new form VersionDialog */ - public VersionDialog(java.awt.Frame parent, boolean modal, boolean verbose) - { - super(parent, modal); - initComponents(); - - this.verbose = verbose; - - textpane_text.setContentType("text/html"); - - StringBuffer sb = new StringBuffer(); - try - { - URL url = getClass().getResource("/res/help/about/about.html"); - if (verbose) - { - System.err.println("" + getClass() + " trying to load about html " + url); - } - - BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); - while (true) - { - String line = reader.readLine(); - if (line == null) break; - sb.append(line); - } - - textpane_text.setText(sb.toString()); - } - catch (Exception e) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, null, e); - } - - } - - /** This method is called from within the constructor to - * initialize the form. - * WARNING: Do NOT modify this code. The content of this method is - * always regenerated by the Form Editor. - */ - // //GEN-BEGIN:initComponents - private void initComponents() - { - jPanel1 = new javax.swing.JPanel(); - textpane_text = new javax.swing.JTextPane(); - jPanel2 = new javax.swing.JPanel(); - bn_close = new javax.swing.JButton(); - - setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); - setTitle("About SVG Salamander"); - jPanel1.setLayout(new java.awt.BorderLayout()); - - textpane_text.setEditable(false); - textpane_text.setPreferredSize(new java.awt.Dimension(400, 300)); - jPanel1.add(textpane_text, java.awt.BorderLayout.CENTER); - - getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER); - - bn_close.setText("Close"); - bn_close.addActionListener(new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent evt) - { - bn_closeActionPerformed(evt); - } - }); - - jPanel2.add(bn_close); - - getContentPane().add(jPanel2, java.awt.BorderLayout.SOUTH); - - pack(); - } - // //GEN-END:initComponents - - private void bn_closeActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_bn_closeActionPerformed - {//GEN-HEADEREND:event_bn_closeActionPerformed - setVisible(false); - dispose(); - }//GEN-LAST:event_bn_closeActionPerformed - - /** - * @param args the command line arguments - */ - public static void main(String args[]) - { - java.awt.EventQueue.invokeLater(new Runnable() - { - public void run() - { - new VersionDialog(new javax.swing.JFrame(), true, true).setVisible(true); - } - }); - } - - // Variables declaration - do not modify//GEN-BEGIN:variables - private javax.swing.JButton bn_close; - private javax.swing.JPanel jPanel1; - private javax.swing.JPanel jPanel2; - private javax.swing.JTextPane textpane_text; - // End of variables declaration//GEN-END:variables - -} --- a/src/com/kitfox/svg/app/ant/SVGToImageAntTask.java +++ /dev/null @@ -1,281 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on January 22, 2005, 10:30 AM - */ - -package com.kitfox.svg.app.ant; - -import java.awt.*; -import java.awt.image.*; -import java.util.*; -import java.util.regex.*; -import java.io.*; -import javax.imageio.*; - -//import com.kitfox.util.*; -//import com.kitfox.util.indexedObject.*; - -import org.apache.tools.ant.*; -import org.apache.tools.ant.types.*; - -import com.kitfox.svg.app.beans.*; -import com.kitfox.svg.*; -import com.kitfox.svg.xml.ColorTable; - -/** - *

Translates a group of SVG files into images.

- * - *

Parameters:

- *
    - *
  • destDir - If present, specifies a directory to write SVG files to. Otherwise - * writes images to directory SVG file was found in - * verbose - If true, prints processing information to the console
  • - *
  • format - File format for output images. The java core javax.imageio.ImageIO - * class is used for creating images, so format strings will depend on what - * files your system is configured to handle. By default, "gif", "jpg" and "png" - * files are guaranteed to be present. If omitted, "png" is used by default.
  • - *
  • backgroundColor - Optional background color. Color can be specified as a standard - * HTML color. That is, as the name of a standard color such as "blue" or - * "limegreen", using the # notation as in #ff00ff for magenta, or in rgb format - * listing the components as in rgb(255, 192, 192) for pink. If omitted, - * background is transparent.
  • - *
  • antiAlias - If set, shapes are drawn using anti-aliasing. Defaults to true.
  • - *
  • interpolation - String describing image interpolation algorithm. Can - * be one of "nearest neighbor", "bilinear" or "bicubic". Defaults to "bicubic".
  • - *
  • width - If greater than 0, determines the width of the written image. Otherwise, - * the width is obtained from the SVG document. Defaults to -1;
  • - *
  • height - If greater than 0, determines the height of the written image. Otherwise, - * the height is obtained from the SVG document. Defaults to -1.
  • - *
  • sizeToFit - If true and the width and height of the output image differ - * from that of the SVG image, the valid area of the SVG image will be resized - * to fit the specified size.
  • - *
  • verbose - If true, prints out diagnostic information about processing. - * Defaults to false.
  • - *
- * - * Example: - * <SVGToImage destDir="${index.java}" format="jpg" verbose="true"> - * <fileset dir="${dir1}"> - * <include name="*.svg"/> - * </fileset> - * <fileset dir="${dir2}"> - * <include name="*.svg"/> - * </fileset> - * </SVGToImage> - * - * - * - * @author kitfox - */ -public class SVGToImageAntTask extends Task -{ - private ArrayList filesets = new ArrayList(); - boolean verbose = false; - File destDir; - private String format = "png"; - Color backgroundColor = null; - int width = -1; - int height = -1; - boolean antiAlias = true; - String interpolation = "bicubic"; - boolean clipToViewBox = false; - boolean sizeToFit = true; - - /** Creates a new instance of IndexLoadObjectsAntTask */ - public SVGToImageAntTask() - { - } - - - public String getFormat() - { - return format; - } - - public void setFormat(String format) - { - this.format = format; - } - - public void setBackgroundColor(String bgColor) - { - this.backgroundColor = ColorTable.parseColor(bgColor); - } - - public void setHeight(int height) - { - this.height = height; - } - - public void setWidth(int width) - { - this.width = width; - } - - public void setAntiAlias(boolean antiAlias) - { - this.antiAlias = antiAlias; - } - - public void setInterpolation(String interpolation) - { - this.interpolation = interpolation; - } - - public void setSizeToFit(boolean sizeToFit) - { - this.sizeToFit = sizeToFit; - } - - public void setClipToViewBox(boolean clipToViewBox) - { - this.clipToViewBox = clipToViewBox; - } - - public void setVerbose(boolean verbose) - { - this.verbose = verbose; - } - - public void setDestDir(File destDir) - { - this.destDir = destDir; - } - - /** - * Adds a set of files. - * @param set - */ - public void addFileset(FileSet set) - { - filesets.add(set); - } - - - - @Override - public void execute() - { - if (verbose) log("Building SVG images"); - - for (FileSet fs : filesets) { - FileScanner scanner = fs.getDirectoryScanner(getProject()); - String[] files = scanner.getIncludedFiles(); - - try - { - File basedir = scanner.getBasedir(); - - if (verbose) log("Scaning " + basedir); - - for (int i = 0; i < files.length; i++) - { -//System.out.println("File " + files[i]); -//System.out.println("BaseDir " + basedir); - translate(basedir, files[i]); - } - } - catch (Exception e) - { - throw new BuildException(e); - } - } - } - - private void translate(File baseDir, String shortName) throws BuildException - { - File source = new File(baseDir, shortName); - - if (verbose) log("Reading file: " + source); - - Matcher matchName = Pattern.compile("(.*)\\.svg", Pattern.CASE_INSENSITIVE).matcher(shortName); - if (matchName.matches()) - { - shortName = matchName.group(1); - } - shortName += "." + format; - - SVGIcon icon = new SVGIcon(); - icon.setSvgURI(source.toURI()); - icon.setAntiAlias(antiAlias); - if (interpolation.equals("nearest neighbor")) - { - icon.setInterpolation(SVGIcon.INTERP_NEAREST_NEIGHBOR); - } - else if (interpolation.equals("bilinear")) - { - icon.setInterpolation(SVGIcon.INTERP_BILINEAR); - } - else if (interpolation.equals("bicubic")) - { - icon.setInterpolation(SVGIcon.INTERP_BICUBIC); - } - - int iconWidth = width > 0 ? width : icon.getIconWidth(); - int iconHeight = height > 0 ? height : icon.getIconHeight(); - icon.setClipToViewbox(clipToViewBox); - icon.setPreferredSize(new Dimension(iconWidth, iconHeight)); - icon.setScaleToFit(sizeToFit); - BufferedImage image = new BufferedImage(iconWidth, iconHeight, BufferedImage.TYPE_INT_ARGB); - Graphics2D g = image.createGraphics(); - - if (backgroundColor != null) - { - g.setColor(backgroundColor); - g.fillRect(0, 0, iconWidth, iconHeight); - } - - g.setClip(0, 0, iconWidth, iconHeight); -// g.fillRect(10, 10, 100, 100); - icon.paintIcon(null, g, 0, 0); - g.dispose(); - - File outFile = destDir == null ? new File(baseDir, shortName) : new File(destDir, shortName); - if (verbose) log("Writing file: " + outFile); - - try - { - ImageIO.write(image, format, outFile); - } - catch (IOException e) - { - log("Error writing image: " + e.getMessage()); - throw new BuildException(e); - } - - - SVGCache.getSVGUniverse().clear(); - } - -} --- a/src/com/kitfox/svg/app/beans/ProportionalLayoutPanel.form +++ /dev/null @@ -1,34 +0,0 @@ - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
--- a/src/com/kitfox/svg/app/beans/ProportionalLayoutPanel.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on May 7, 2005, 4:15 AM - */ - -package com.kitfox.svg.app.beans; - -import java.awt.*; -import javax.swing.*; - -/** - * Panel based on the null layout. Allows editing with absolute layout. When - * instanced, records layout dimensions of all subcomponents. Then, if the - * panel is ever resized, scales all children to fit new size. - * - * @author kitfox - */ -public class ProportionalLayoutPanel extends javax.swing.JPanel -{ - public static final long serialVersionUID = 1; - - //Margins to leave on sides of panel, expressed in fractions [0 1] - float topMargin; - float bottomMargin; - float leftMargin; - float rightMargin; - - /** Creates new form ProportionalLayoutPanel */ - public ProportionalLayoutPanel() - { - initComponents(); - } - - @Override - public void addNotify() - { - super.addNotify(); - - Rectangle rect = this.getBounds(); - JOptionPane.showMessageDialog(this, "" + rect); - } - - - /** This method is called from within the constructor to - * initialize the form. - * WARNING: Do NOT modify this code. The content of this method is - * always regenerated by the Form Editor. - */ - // //GEN-BEGIN:initComponents - private void initComponents() - { - jPanel1 = new javax.swing.JPanel(); - - setLayout(null); - - addComponentListener(new java.awt.event.ComponentAdapter() - { - @Override - public void componentResized(java.awt.event.ComponentEvent evt) - { - formComponentResized(evt); - } - @Override - public void componentShown(java.awt.event.ComponentEvent evt) - { - formComponentShown(evt); - } - }); - - add(jPanel1); - jPanel1.setBounds(80, 90, 280, 160); - - } - // //GEN-END:initComponents - - private void formComponentShown(java.awt.event.ComponentEvent evt)//GEN-FIRST:event_formComponentShown - {//GEN-HEADEREND:event_formComponentShown - JOptionPane.showMessageDialog(this, "" + getWidth() + ", " + getHeight()); - - }//GEN-LAST:event_formComponentShown - - private void formComponentResized(java.awt.event.ComponentEvent evt)//GEN-FIRST:event_formComponentResized - {//GEN-HEADEREND:event_formComponentResized -// TODO add your handling code here: - }//GEN-LAST:event_formComponentResized - - - // Variables declaration - do not modify//GEN-BEGIN:variables - private javax.swing.JPanel jPanel1; - // End of variables declaration//GEN-END:variables - -} --- a/src/com/kitfox/svg/app/beans/SVGIcon.java +++ /dev/null @@ -1,556 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on April 21, 2005, 10:45 AM - */ - -package com.kitfox.svg.app.beans; - -import com.kitfox.svg.SVGCache; -import com.kitfox.svg.SVGDiagram; -import com.kitfox.svg.SVGException; -import com.kitfox.svg.SVGUniverse; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Image; -import java.awt.Rectangle; -import java.awt.RenderingHints; -import java.awt.geom.AffineTransform; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeSupport; -import java.net.URI; -import javax.swing.ImageIcon; - - -/** - * - * @author kitfox - */ -public class SVGIcon extends ImageIcon -{ - public static final long serialVersionUID = 1; - - public static final String PROP_AUTOSIZE = "PROP_AUTOSIZE"; - - private final PropertyChangeSupport changes = new PropertyChangeSupport(this); - - SVGUniverse svgUniverse = SVGCache.getSVGUniverse(); - public static final int INTERP_NEAREST_NEIGHBOR = 0; - public static final int INTERP_BILINEAR = 1; - public static final int INTERP_BICUBIC = 2; - - private boolean antiAlias; - private int interpolation = INTERP_NEAREST_NEIGHBOR; - private boolean clipToViewbox; - - URI svgURI; - -// private boolean scaleToFit; - AffineTransform scaleXform = new AffineTransform(); - - public static final int AUTOSIZE_NONE = 0; - public static final int AUTOSIZE_HORIZ = 1; - public static final int AUTOSIZE_VERT = 2; - public static final int AUTOSIZE_BESTFIT = 3; - public static final int AUTOSIZE_STRETCH = 4; - private int autosize = AUTOSIZE_NONE; - - Dimension preferredSize; - - /** Creates a new instance of SVGIcon */ - public SVGIcon() - { - } - - public void addPropertyChangeListener(PropertyChangeListener p) - { - changes.addPropertyChangeListener(p); - } - - public void removePropertyChangeListener(PropertyChangeListener p) - { - changes.removePropertyChangeListener(p); - } - - @Override - public Image getImage() - { - BufferedImage bi = new BufferedImage(getIconWidth(), getIconHeight(), BufferedImage.TYPE_INT_ARGB); - paintIcon(null, bi.getGraphics(), 0, 0); - return bi; - } - - /** - * @return height of this icon - */ - public int getIconHeightIgnoreAutosize() - { - if (preferredSize != null && - (autosize == AUTOSIZE_VERT || autosize == AUTOSIZE_STRETCH - || autosize == AUTOSIZE_BESTFIT)) - { - return preferredSize.height; - } - - SVGDiagram diagram = svgUniverse.getDiagram(svgURI); - if (diagram == null) - { - return 0; - } - return (int)diagram.getHeight(); - } - - /** - * @return width of this icon - */ - - public int getIconWidthIgnoreAutosize() - { - if (preferredSize != null && - (autosize == AUTOSIZE_HORIZ || autosize == AUTOSIZE_STRETCH - || autosize == AUTOSIZE_BESTFIT)) - { - return preferredSize.width; - } - - SVGDiagram diagram = svgUniverse.getDiagram(svgURI); - if (diagram == null) - { - return 0; - } - return (int)diagram.getWidth(); - } - - private boolean isAutoSizeBestFitUseFixedHeight(final int iconWidthIgnoreAutosize, final int iconHeightIgnoreAutosize, - final SVGDiagram diagram) - { - return iconHeightIgnoreAutosize/diagram.getHeight() < iconWidthIgnoreAutosize/diagram.getWidth(); - } - - @Override - public int getIconWidth() - { - final int iconWidthIgnoreAutosize = getIconWidthIgnoreAutosize(); - final int iconHeightIgnoreAutosize = getIconHeightIgnoreAutosize(); - final SVGDiagram diagram = svgUniverse.getDiagram(svgURI); - if (preferredSize != null && (autosize == AUTOSIZE_VERT || - (autosize == AUTOSIZE_BESTFIT && isAutoSizeBestFitUseFixedHeight(iconWidthIgnoreAutosize, iconHeightIgnoreAutosize, diagram)))) - { - final double aspectRatio = diagram.getHeight()/diagram.getWidth(); - return (int)(iconHeightIgnoreAutosize / aspectRatio); - } - else - { - return iconWidthIgnoreAutosize; - } - } - - @Override - public int getIconHeight() - { - final int iconWidthIgnoreAutosize = getIconWidthIgnoreAutosize(); - final int iconHeightIgnoreAutosize = getIconHeightIgnoreAutosize(); - final SVGDiagram diagram = svgUniverse.getDiagram(svgURI); - if (preferredSize != null && (autosize == AUTOSIZE_HORIZ || - (autosize == AUTOSIZE_BESTFIT && !isAutoSizeBestFitUseFixedHeight(iconWidthIgnoreAutosize, iconHeightIgnoreAutosize, diagram)))) - { - final double aspectRatio = diagram.getHeight()/diagram.getWidth(); - return (int)(iconWidthIgnoreAutosize * aspectRatio); - } - else - { - return iconHeightIgnoreAutosize; - } - } - - - /** - * Draws the icon to the specified component. - * @param comp - Component to draw icon to. This is ignored by SVGIcon, and can be set to null; only gg is used for drawing the icon - * @param gg - Graphics context to render SVG content to - * @param x - X coordinate to draw icon - * @param y - Y coordinate to draw icon - */ - @Override - public void paintIcon(Component comp, Graphics gg, int x, int y) - { - //Copy graphics object so that - Graphics2D g = (Graphics2D)gg.create(); - paintIcon(comp, g, x, y); - g.dispose(); - } - - private void paintIcon(Component comp, Graphics2D g, int x, int y) - { - Object oldAliasHint = g.getRenderingHint(RenderingHints.KEY_ANTIALIASING); - g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, antiAlias ? RenderingHints.VALUE_ANTIALIAS_ON : RenderingHints.VALUE_ANTIALIAS_OFF); - - Object oldInterpolationHint = g.getRenderingHint(RenderingHints.KEY_INTERPOLATION); - switch (interpolation) - { - case INTERP_NEAREST_NEIGHBOR: - g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); - break; - case INTERP_BILINEAR: - g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); - break; - case INTERP_BICUBIC: - g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); - break; - } - - - SVGDiagram diagram = svgUniverse.getDiagram(svgURI); - if (diagram == null) - { - return; - } - - g.translate(x, y); - diagram.setIgnoringClipHeuristic(!clipToViewbox); - if (clipToViewbox) - { - g.setClip(new Rectangle2D.Float(0, 0, diagram.getWidth(), diagram.getHeight())); - } - - - if (autosize == AUTOSIZE_NONE) - { - try - { - diagram.render(g); - g.translate(-x, -y); - g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, oldAliasHint); - } - catch (Exception e) - { - throw new RuntimeException(e); - } - return; - } - - final int width = getIconWidthIgnoreAutosize(); - final int height = getIconHeightIgnoreAutosize(); -// int width = getWidth(); -// int height = getHeight(); - - if (width == 0 || height == 0) - { - return; - } - -// if (width == 0 || height == 0) -// { -// //Chances are we're rendering offscreen -// Dimension dim = getSize(); -// width = dim.width; -// height = dim.height; -// return; -// } - -// g.setClip(0, 0, width, height); - - -// final Rectangle2D.Double rect = new Rectangle2D.Double(); -// diagram.getViewRect(rect); -// -// scaleXform.setToScale(width / rect.width, height / rect.height); - double diaWidth = diagram.getWidth(); - double diaHeight = diagram.getHeight(); - - double scaleW = 1; - double scaleH = 1; - if (autosize == AUTOSIZE_BESTFIT) - { - scaleW = scaleH = (height / diaHeight < width / diaWidth) - ? height / diaHeight : width / diaWidth; - } - else if (autosize == AUTOSIZE_HORIZ) - { - scaleW = scaleH = width / diaWidth; - } - else if (autosize == AUTOSIZE_VERT) - { - scaleW = scaleH = height / diaHeight; - } - else if (autosize == AUTOSIZE_STRETCH) - { - scaleW = width / diaWidth; - scaleH = height / diaHeight; - } - scaleXform.setToScale(scaleW, scaleH); - - AffineTransform oldXform = g.getTransform(); - g.transform(scaleXform); - - try - { - diagram.render(g); - } - catch (SVGException e) - { - throw new RuntimeException(e); - } - - g.setTransform(oldXform); - - - g.translate(-x, -y); - - g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, oldAliasHint); - if (oldInterpolationHint != null) - { - g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, oldInterpolationHint); - } - } - - /** - * @return the universe this icon draws it's SVGDiagrams from - */ - public SVGUniverse getSvgUniverse() - { - return svgUniverse; - } - - public void setSvgUniverse(SVGUniverse svgUniverse) - { - SVGUniverse old = this.svgUniverse; - this.svgUniverse = svgUniverse; - changes.firePropertyChange("svgUniverse", old, svgUniverse); - } - - /** - * @return the uni of the document being displayed by this icon - */ - public URI getSvgURI() - { - return svgURI; - } - - /** - * Loads an SVG document from a URI. - * @param svgURI - URI to load document from - */ - public void setSvgURI(URI svgURI) - { - URI old = this.svgURI; - this.svgURI = svgURI; - - SVGDiagram diagram = svgUniverse.getDiagram(svgURI); - if (diagram != null) - { - Dimension size = getPreferredSize(); - if (size == null) - { - size = new Dimension((int)diagram.getRoot().getDeviceWidth(), (int)diagram.getRoot().getDeviceHeight()); - } - diagram.setDeviceViewport(new Rectangle(0, 0, size.width, size.height)); - } - - changes.firePropertyChange("svgURI", old, svgURI); - } - - /** - * Loads an SVG document from the classpath. This function is equivilant to - * setSvgURI(new URI(getClass().getResource(resourcePath).toString()); - * @param resourcePath - resource to load - */ - public void setSvgResourcePath(String resourcePath) - { - URI old = this.svgURI; - - try - { - svgURI = new URI(getClass().getResource(resourcePath).toString()); - changes.firePropertyChange("svgURI", old, svgURI); - - SVGDiagram diagram = svgUniverse.getDiagram(svgURI); - if (diagram != null) - { - diagram.setDeviceViewport(new Rectangle(0, 0, preferredSize.width, preferredSize.height)); - } - - } - catch (Exception e) - { - svgURI = old; - } - } - - /** - * If this SVG document has a viewbox, if scaleToFit is set, will scale the viewbox to match the - * preferred size of this icon - * @deprecated - * @return - */ - public boolean isScaleToFit() - { - return autosize == AUTOSIZE_STRETCH; - } - - /** - * @deprecated - */ - public void setScaleToFit(boolean scaleToFit) - { - setAutosize(AUTOSIZE_STRETCH); -// boolean old = this.scaleToFit; -// this.scaleToFit = scaleToFit; -// firePropertyChange("scaleToFit", old, scaleToFit); - } - - public Dimension getPreferredSize() - { - if (preferredSize == null) - { - SVGDiagram diagram = svgUniverse.getDiagram(svgURI); - if (diagram != null) - { - //preferredSize = new Dimension((int)diagram.getWidth(), (int)diagram.getHeight()); - setPreferredSize(new Dimension((int)diagram.getWidth(), (int)diagram.getHeight())); - } - } - - return new Dimension(preferredSize); - } - - public void setPreferredSize(Dimension preferredSize) - { - Dimension old = this.preferredSize; - this.preferredSize = preferredSize; - - SVGDiagram diagram = svgUniverse.getDiagram(svgURI); - if (diagram != null) - { - diagram.setDeviceViewport(new Rectangle(0, 0, preferredSize.width, preferredSize.height)); - } - - changes.firePropertyChange("preferredSize", old, preferredSize); - } - - - /** - * @return true if antiAliasing is turned on. - * @deprecated - */ - public boolean getUseAntiAlias() - { - return getAntiAlias(); - } - - /** - * @param antiAlias true to use antiAliasing. - * @deprecated - */ - public void setUseAntiAlias(boolean antiAlias) - { - setAntiAlias(antiAlias); - } - - /** - * @return true if antiAliasing is turned on. - */ - public boolean getAntiAlias() - { - return antiAlias; - } - - /** - * @param antiAlias true to use antiAliasing. - */ - public void setAntiAlias(boolean antiAlias) - { - boolean old = this.antiAlias; - this.antiAlias = antiAlias; - changes.firePropertyChange("antiAlias", old, antiAlias); - } - - /** - * @return interpolation used in rescaling images - */ - public int getInterpolation() - { - return interpolation; - } - - /** - * @param interpolation Interpolation value used in rescaling images. - * Should be one of - * INTERP_NEAREST_NEIGHBOR - Fastest, one pixel resampling, poor quality - * INTERP_BILINEAR - four pixel resampling - * INTERP_BICUBIC - Slowest, nine pixel resampling, best quality - */ - public void setInterpolation(int interpolation) - { - int old = this.interpolation; - this.interpolation = interpolation; - changes.firePropertyChange("interpolation", old, interpolation); - } - - /** - * clipToViewbox will set a clip box equivilant to the SVG's viewbox before - * rendering. - */ - public boolean isClipToViewbox() - { - return clipToViewbox; - } - - public void setClipToViewbox(boolean clipToViewbox) - { - this.clipToViewbox = clipToViewbox; - } - - /** - * @return the autosize - */ - public int getAutosize() - { - return autosize; - } - - /** - * @param autosize the autosize to set - */ - public void setAutosize(int autosize) - { - int oldAutosize = this.autosize; - this.autosize = autosize; - changes.firePropertyChange(PROP_AUTOSIZE, oldAutosize, autosize); - } - -} --- a/src/com/kitfox/svg/app/beans/SVGPanel.form +++ /dev/null @@ -1,17 +0,0 @@ - - -
- - - - - - - - - - - - - - --- a/src/com/kitfox/svg/app/beans/SVGPanel.java +++ /dev/null @@ -1,338 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on April 21, 2005, 10:43 AM - */ - -package com.kitfox.svg.app.beans; - -import com.kitfox.svg.*; -import java.awt.*; -import java.awt.geom.*; -import java.net.*; -import javax.swing.*; - -/** - * - * @author kitfox - */ -public class SVGPanel extends JPanel -{ - public static final long serialVersionUID = 1; - public static final String PROP_AUTOSIZE = "PROP_AUTOSIZE"; - - SVGUniverse svgUniverse = SVGCache.getSVGUniverse(); - - private boolean antiAlias; - -// private String svgPath; - URI svgURI; - -// private boolean scaleToFit; - AffineTransform scaleXform = new AffineTransform(); - - public static final int AUTOSIZE_NONE = 0; - public static final int AUTOSIZE_HORIZ = 1; - public static final int AUTOSIZE_VERT = 2; - public static final int AUTOSIZE_BESTFIT = 3; - public static final int AUTOSIZE_STRETCH = 4; - private int autosize = AUTOSIZE_NONE; - - /** Creates new form SVGIcon */ - public SVGPanel() - { - initComponents(); - } - - public int getSVGHeight() - { - if (autosize == AUTOSIZE_VERT || autosize == AUTOSIZE_STRETCH - || autosize == AUTOSIZE_BESTFIT) - { - return getPreferredSize().height; - } - - SVGDiagram diagram = svgUniverse.getDiagram(svgURI); - if (diagram == null) - { - return 0; - } - return (int)diagram.getHeight(); - } - - public int getSVGWidth() - { - if (autosize == AUTOSIZE_HORIZ || autosize == AUTOSIZE_STRETCH - || autosize == AUTOSIZE_BESTFIT) - { - return getPreferredSize().width; - } - - SVGDiagram diagram = svgUniverse.getDiagram(svgURI); - if (diagram == null) - { - return 0; - } - return (int)diagram.getWidth(); - } - - @Override - public void paintComponent(Graphics gg) - { - super.paintComponent(gg); - - Graphics2D g = (Graphics2D)gg.create(); - paintComponent(g); - g.dispose(); - } - - private void paintComponent(Graphics2D g) - { - Object oldAliasHint = g.getRenderingHint(RenderingHints.KEY_ANTIALIASING); - g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, antiAlias ? RenderingHints.VALUE_ANTIALIAS_ON : RenderingHints.VALUE_ANTIALIAS_OFF); - - - SVGDiagram diagram = svgUniverse.getDiagram(svgURI); - if (diagram == null) - { - return; - } - - if (autosize == AUTOSIZE_NONE) - { - try - { - diagram.render(this, g); - g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, oldAliasHint); - } - catch (SVGException e) - { - throw new RuntimeException(e); - } - return; - } - - Dimension dim = getSize(); - final int width = dim.width; - final int height = dim.height; - -// final Rectangle2D.Double rect = new Rectangle2D.Double(); -// diagram.getViewRect(rect); - - double diaWidth = diagram.getWidth(); - double diaHeight = diagram.getHeight(); - - double scaleW = 1; - double scaleH = 1; - if (autosize == AUTOSIZE_BESTFIT) - { - scaleW = scaleH = (height / diaHeight < width / diaWidth) - ? height / diaHeight : width / diaWidth; - } - else if (autosize == AUTOSIZE_HORIZ) - { - scaleW = scaleH = width / diaWidth; - } - else if (autosize == AUTOSIZE_VERT) - { - scaleW = scaleH = height / diaHeight; - } - else if (autosize == AUTOSIZE_STRETCH) - { - scaleW = width / diaWidth; - scaleH = height / diaHeight; - } - scaleXform.setToScale(scaleW, scaleH); - - AffineTransform oldXform = g.getTransform(); - g.transform(scaleXform); - - try - { - diagram.render(g); - } - catch (SVGException e) - { - throw new RuntimeException(e); - } - - g.setTransform(oldXform); - - g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, oldAliasHint); - } - - public SVGUniverse getSvgUniverse() - { - return svgUniverse; - } - - public void setSvgUniverse(SVGUniverse svgUniverse) - { - SVGUniverse old = this.svgUniverse; - this.svgUniverse = svgUniverse; - firePropertyChange("svgUniverse", old, svgUniverse); - } - - public URI getSvgURI() - { - return svgURI; - } - - public void setSvgURI(URI svgURI) - { - URI old = this.svgURI; - this.svgURI = svgURI; - firePropertyChange("svgURI", old, svgURI); - } - - /** - * Most resources your component will want to access will be resources on your classpath. - * This method will interpret the passed string as a path in the classpath and use - * Class.getResource() to determine the URI of the SVG. - */ - public void setSvgResourcePath(String resourcePath) throws SVGException - { - URI old = this.svgURI; - - try - { - svgURI = new URI(getClass().getResource(resourcePath).toString()); -//System.err.println("SVGPanel: new URI " + svgURI + " from path " + resourcePath); - - firePropertyChange("svgURI", old, svgURI); - - repaint(); - } - catch (Exception e) - { - throw new SVGException("Could not resolve path " + resourcePath, e); -// svgURI = old; - } - } - - /** - * If this SVG document has a viewbox, if scaleToFit is set, will scale the viewbox to match the - * preferred size of this icon - * @deprecated - * @return - */ - public boolean isScaleToFit() - { - return autosize == AUTOSIZE_STRETCH; - } - - /** - * @deprecated - */ - public void setScaleToFit(boolean scaleToFit) - { - setAutosize(AUTOSIZE_STRETCH); -// boolean old = this.scaleToFit; -// this.scaleToFit = scaleToFit; -// firePropertyChange("scaleToFit", old, scaleToFit); - } - - /** - * @return true if antiAliasing is turned on. - * @deprecated - */ - public boolean getUseAntiAlias() - { - return getAntiAlias(); - } - - /** - * @param antiAlias true to use antiAliasing. - * @deprecated - */ - public void setUseAntiAlias(boolean antiAlias) - { - setAntiAlias(antiAlias); - } - - /** - * @return true if antiAliasing is turned on. - */ - public boolean getAntiAlias() - { - return antiAlias; - } - - /** - * @param antiAlias true to use antiAliasing. - */ - public void setAntiAlias(boolean antiAlias) - { - boolean old = this.antiAlias; - this.antiAlias = antiAlias; - firePropertyChange("antiAlias", old, antiAlias); - } - - /** - * @return the autosize - */ - public int getAutosize() - { - return autosize; - } - - /** - * @param autosize the autosize to set - */ - public void setAutosize(int autosize) - { - int oldAutosize = this.autosize; - this.autosize = autosize; - firePropertyChange(PROP_AUTOSIZE, oldAutosize, autosize); - } - - /** This method is called from within the constructor to - * initialize the form. - * WARNING: Do NOT modify this code. The content of this method is - * always regenerated by the Form Editor. - */ - // //GEN-BEGIN:initComponents - private void initComponents() - { - - setLayout(new java.awt.BorderLayout()); - - } - // //GEN-END:initComponents - - - // Variables declaration - do not modify//GEN-BEGIN:variables - // End of variables declaration//GEN-END:variables - - -} --- a/src/com/kitfox/svg/app/data/Handler.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - */ - -package com.kitfox.svg.app.data; - -import com.kitfox.svg.SVGConst; -import com.kitfox.svg.util.Base64InputStream; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.net.URLConnection; -import java.net.URLStreamHandler; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * - * @author kitfox - */ -public class Handler extends URLStreamHandler -{ - class Connection extends URLConnection - { - String mime; - byte[] buf; - - public Connection(URL url) - { - super(url); - - String path = url.getPath(); - int idx = path.indexOf(';'); - mime = path.substring(0, idx); - String content = path.substring(idx + 1); - - if (content.startsWith("base64,")) - { - content = content.substring(7); - try - { -//byte[] buf2 = new sun.misc.BASE64Decoder().decodeBuffer(content); -//buf = new sun.misc.BASE64Decoder().decodeBuffer(content); - - ByteArrayInputStream bis = new ByteArrayInputStream(content.getBytes()); - Base64InputStream b64is = new Base64InputStream(bis); - - ByteArrayOutputStream bout = new ByteArrayOutputStream(); - byte[] tmp = new byte[2056]; - for (int size = b64is.read(tmp); size != -1; size = b64is.read(tmp)) - { - bout.write(tmp, 0, size); - } - buf = bout.toByteArray(); - } - catch (IOException e) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, null, e); - } - } - } - - @Override - public void connect() throws IOException - { - } - - @Override - public String getHeaderField(String name) - { - if ("content-type".equals(name)) - { - return mime; - } - - return super.getHeaderField(name); - } - - @Override - public InputStream getInputStream() throws IOException - { - return new ByteArrayInputStream(buf); - } - -// public Object getContent() throws IOException -// { -// BufferedImage img = ImageIO.read(getInputStream()); -// } - } - - @Override - protected URLConnection openConnection(URL u) throws IOException - { - return new Connection(u); - } - -} --- a/src/com/kitfox/svg/app/data/HandlerFactory.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - */ - -package com.kitfox.svg.app.data; - -import java.net.URLStreamHandler; -import java.net.URLStreamHandlerFactory; - -/** - * - * @author kitfox - */ -public class HandlerFactory implements URLStreamHandlerFactory -{ - static Handler handler = new Handler(); - - public URLStreamHandler createURLStreamHandler(String protocol) - { - if ("data".equals(protocol)) - { - return handler; - } - return null; - } -} --- a/src/com/kitfox/svg/composite/AdobeComposite.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on April 1, 2004, 6:40 AM - */ - -package com.kitfox.svg.composite; - -import com.kitfox.svg.SVGConst; -import java.awt.*; -import java.awt.image.*; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class AdobeComposite implements Composite -{ - public static final int CT_NORMAL = 0; - public static final int CT_MULTIPLY = 1; - public static final int CT_LAST = 2; - - final int compositeType; - final float extraAlpha; - - /** - * Creates a new instance of AdobeComposite - * @param compositeType - * @param extraAlpha - */ - public AdobeComposite(int compositeType, float extraAlpha) - { - this.compositeType = compositeType; - this.extraAlpha = extraAlpha; - - if (compositeType < 0 || compositeType >= CT_LAST) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, "Invalid composite type"); - } - - if (extraAlpha < 0f || extraAlpha > 1f) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, "Invalid alpha"); - } - } - - public int getCompositeType() { return compositeType; } - - public CompositeContext createContext(ColorModel srcColorModel, ColorModel dstColorModel, RenderingHints hints) - { - return new AdobeCompositeContext(compositeType, extraAlpha); - } - -} --- a/src/com/kitfox/svg/composite/AdobeCompositeContext.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on April 1, 2004, 6:41 AM - */ - -package com.kitfox.svg.composite; - -import java.awt.*; -import java.awt.image.*; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class AdobeCompositeContext implements CompositeContext -{ - final int compositeType; - final float extraAlpha; - - float[] rgba_src = new float[4]; - float[] rgba_dstIn = new float[4]; - float[] rgba_dstOut = new float[4]; - - /** Creates a new instance of AdobeCompositeContext - * @param compositeType - * @param extraAlpha - */ - public AdobeCompositeContext(int compositeType, float extraAlpha) - { - this.compositeType = compositeType; - this.extraAlpha = extraAlpha; - - rgba_dstOut[3] = 1f; - } - - public void compose(Raster src, Raster dstIn, WritableRaster dstOut) - { - int width = src.getWidth(); - int height = src.getHeight(); - - for (int j = 0; j < height; j++) - { - for (int i = 0; i < width; i++) - { - src.getPixel(i, j, rgba_src); - dstIn.getPixel(i, j, rgba_dstIn); - - //Ignore transparent pixels - if (rgba_src[3] == 0) - { -// dstOut.setPixel(i, j, rgba_dstIn); - continue; - } - - float alpha = rgba_src[3]; - - switch (compositeType) - { - default: - case AdobeComposite.CT_NORMAL: - rgba_dstOut[0] = rgba_src[0] * alpha + rgba_dstIn[0] * (1f - alpha); - rgba_dstOut[1] = rgba_src[1] * alpha + rgba_dstIn[1] * (1f - alpha); - rgba_dstOut[2] = rgba_src[2] * alpha + rgba_dstIn[2] * (1f - alpha); - break; - case AdobeComposite.CT_MULTIPLY: - rgba_dstOut[0] = rgba_src[0] * rgba_dstIn[0] * alpha + rgba_dstIn[0] * (1f - alpha); - rgba_dstOut[1] = rgba_src[1] * rgba_dstIn[1] * alpha + rgba_dstIn[1] * (1f - alpha); - rgba_dstOut[2] = rgba_src[2] * rgba_dstIn[2] * alpha + rgba_dstIn[2] * (1f - alpha); - break; - } - } - } - } - - public void dispose() { - } - -} --- a/src/com/kitfox/svg/package-info.java +++ /dev/null @@ -1,9 +0,0 @@ -/** - * Provides the nodes of an SVG scene graph. This graph can be queried, updated - * and picked against at runtime. See the online docs for instructions on - * how to use SVGSalamander - * - * @author Mark McKay (C) 2005 - */ - -package com.kitfox.svg; \ No newline at end of file --- a/src/com/kitfox/svg/pathcmd/Arc.java +++ /dev/null @@ -1,283 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on January 26, 2004, 8:40 PM - */ - -package com.kitfox.svg.pathcmd; - -//import org.apache.batik.ext.awt.geom.ExtendedGeneralPath; -import java.awt.*; -import java.awt.geom.*; - -/** - * This is a little used SVG function, as most editors will save curves as - * Beziers. To reduce the need to rely on the Batik library, this functionallity - * is being bypassed for the time being. In the future, it would be nice to - * extend the GeneralPath command to include the arcTo ability provided by Batik. - * - * @author Mark McKay - * @author Mark McKay - */ -public class Arc extends PathCommand -{ - - public float rx = 0f; - public float ry = 0f; - public float xAxisRot = 0f; - public boolean largeArc = false; - public boolean sweep = false; - public float x = 0f; - public float y = 0f; - - /** Creates a new instance of MoveTo */ - public Arc() { - } - - public Arc(boolean isRelative, float rx, float ry, float xAxisRot, boolean largeArc, boolean sweep, float x, float y) { - super(isRelative); - this.rx = rx; - this.ry = ry; - this.xAxisRot = xAxisRot; - this.largeArc = largeArc; - this.sweep = sweep; - this.x = x; - this.y = y; - } - -// public void appendPath(ExtendedGeneralPath path, BuildHistory hist) - @Override - public void appendPath(GeneralPath path, BuildHistory hist) - { - float offx = isRelative ? hist.lastPoint.x : 0f; - float offy = isRelative ? hist.lastPoint.y : 0f; - - arcTo(path, rx, ry, xAxisRot, largeArc, sweep, - x + offx, y + offy, - hist.lastPoint.x, hist.lastPoint.y); -// path.lineTo(x + offx, y + offy); -// hist.setPoint(x + offx, y + offy); - hist.setLastPoint(x + offx, y + offy); - hist.setLastKnot(x + offx, y + offy); - } - - @Override - public int getNumKnotsAdded() - { - return 6; - } - - /** - * Adds an elliptical arc, defined by two radii, an angle from the - * x-axis, a flag to choose the large arc or not, a flag to - * indicate if we increase or decrease the angles and the final - * point of the arc. - * - * @param path The path that the arc will be appended to. - * - * @param rx the x radius of the ellipse - * @param ry the y radius of the ellipse - * - * @param angle the angle from the x-axis of the current - * coordinate system to the x-axis of the ellipse in degrees. - * - * @param largeArcFlag the large arc flag. If true the arc - * spanning less than or equal to 180 degrees is chosen, otherwise - * the arc spanning greater than 180 degrees is chosen - * - * @param sweepFlag the sweep flag. If true the line joining - * center to arc sweeps through decreasing angles otherwise it - * sweeps through increasing angles - * - * @param x the absolute x coordinate of the final point of the arc. - * @param y the absolute y coordinate of the final point of the arc. - * @param x0 - The absolute x coordinate of the initial point of the arc. - * @param y0 - The absolute y coordinate of the initial point of the arc. - */ - public void arcTo(GeneralPath path, float rx, float ry, - float angle, - boolean largeArcFlag, - boolean sweepFlag, - float x, float y, float x0, float y0) - { - - // Ensure radii are valid - if (rx == 0 || ry == 0) { - path.lineTo((float) x, (float) y); - return; - } - - if (x0 == x && y0 == y) { - // If the endpoints (x, y) and (x0, y0) are identical, then this - // is equivalent to omitting the elliptical arc segment entirely. - return; - } - - Arc2D arc = computeArc(x0, y0, rx, ry, angle, - largeArcFlag, sweepFlag, x, y); - if (arc == null) return; - - AffineTransform t = AffineTransform.getRotateInstance - (Math.toRadians(angle), arc.getCenterX(), arc.getCenterY()); - Shape s = t.createTransformedShape(arc); - path.append(s, true); - } - - - /** - * This constructs an unrotated Arc2D from the SVG specification of an - * Elliptical arc. To get the final arc you need to apply a rotation - * transform such as: - * - * AffineTransform.getRotateInstance - * (angle, arc.getX()+arc.getWidth()/2, arc.getY()+arc.getHeight()/2); - * - * @param x0 origin of arc in x - * @param y0 origin of arc in y - * @param rx radius of arc in x - * @param ry radius of arc in y - * @param angle number of radians in arc - * @param largeArcFlag - * @param sweepFlag - * @param x ending coordinate of arc in x - * @param y ending coordinate of arc in y - * @return arc shape - * - */ - public static Arc2D computeArc(double x0, double y0, - double rx, double ry, - double angle, - boolean largeArcFlag, - boolean sweepFlag, - double x, double y) { - // - // Elliptical arc implementation based on the SVG specification notes - // - - // Compute the half distance between the current and the final point - double dx2 = (x0 - x) / 2.0; - double dy2 = (y0 - y) / 2.0; - // Convert angle from degrees to radians - angle = Math.toRadians(angle % 360.0); - double cosAngle = Math.cos(angle); - double sinAngle = Math.sin(angle); - - // - // Step 1 : Compute (x1, y1) - // - double x1 = (cosAngle * dx2 + sinAngle * dy2); - double y1 = (-sinAngle * dx2 + cosAngle * dy2); - // Ensure radii are large enough - rx = Math.abs(rx); - ry = Math.abs(ry); - double Prx = rx * rx; - double Pry = ry * ry; - double Px1 = x1 * x1; - double Py1 = y1 * y1; - // check that radii are large enough - double radiiCheck = Px1/Prx + Py1/Pry; - if (radiiCheck > 1) { - rx = Math.sqrt(radiiCheck) * rx; - ry = Math.sqrt(radiiCheck) * ry; - Prx = rx * rx; - Pry = ry * ry; - } - - // - // Step 2 : Compute (cx1, cy1) - // - double sign = (largeArcFlag == sweepFlag) ? -1 : 1; - double sq = ((Prx*Pry)-(Prx*Py1)-(Pry*Px1)) / ((Prx*Py1)+(Pry*Px1)); - sq = (sq < 0) ? 0 : sq; - double coef = (sign * Math.sqrt(sq)); - double cx1 = coef * ((rx * y1) / ry); - double cy1 = coef * -((ry * x1) / rx); - - // - // Step 3 : Compute (cx, cy) from (cx1, cy1) - // - double sx2 = (x0 + x) / 2.0; - double sy2 = (y0 + y) / 2.0; - double cx = sx2 + (cosAngle * cx1 - sinAngle * cy1); - double cy = sy2 + (sinAngle * cx1 + cosAngle * cy1); - - // - // Step 4 : Compute the angleStart (angle1) and the angleExtent (dangle) - // - double ux = (x1 - cx1) / rx; - double uy = (y1 - cy1) / ry; - double vx = (-x1 - cx1) / rx; - double vy = (-y1 - cy1) / ry; - double p, n; - // Compute the angle start - n = Math.sqrt((ux * ux) + (uy * uy)); - p = ux; // (1 * ux) + (0 * uy) - sign = (uy < 0) ? -1d : 1d; - double angleStart = Math.toDegrees(sign * Math.acos(p / n)); - - // Compute the angle extent - n = Math.sqrt((ux * ux + uy * uy) * (vx * vx + vy * vy)); - p = ux * vx + uy * vy; - sign = (ux * vy - uy * vx < 0) ? -1d : 1d; - double angleExtent = Math.toDegrees(sign * Math.acos(p / n)); - if(!sweepFlag && angleExtent > 0) { - angleExtent -= 360f; - } else if (sweepFlag && angleExtent < 0) { - angleExtent += 360f; - } - angleExtent %= 360f; - angleStart %= 360f; - - // - // We can now build the resulting Arc2D in double precision - // - Arc2D.Double arc = new Arc2D.Double(); - arc.x = cx - rx; - arc.y = cy - ry; - arc.width = rx * 2.0; - arc.height = ry * 2.0; - arc.start = -angleStart; - arc.extent = -angleExtent; - - return arc; - } - - @Override - public String toString() - { - return "A " + rx + " " + ry - + " " + xAxisRot + " " + largeArc - + " " + sweep - + " " + x + " " + y; - } -} --- a/src/com/kitfox/svg/pathcmd/BuildHistory.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on January 26, 2004, 9:18 PM - */ -package com.kitfox.svg.pathcmd; - -import java.awt.geom.Point2D; - -/** - * When building a path from command segments, most need to cache information - * (such as the point finished at) for future commands. This structure allows - * that - * - * @author Mark McKay - * @author Mark McKay - */ -public class BuildHistory -{ - -// Point2D.Float[] history = new Point2D.Float[2]; -// Point2D.Float[] history = {new Point2D.Float(), new Point2D.Float()}; -// Point2D.Float start = new Point2D.Float(); - Point2D.Float startPoint = new Point2D.Float(); - Point2D.Float lastPoint = new Point2D.Float(); - Point2D.Float lastKnot = new Point2D.Float(); - boolean init; - //int length = 0; - - /** - * Creates a new instance of BuildHistory - */ - public BuildHistory() - { - } - - public void setStartPoint(float x, float y) - { - startPoint.setLocation(x, y); - } - - public void setLastPoint(float x, float y) - { - lastPoint.setLocation(x, y); - } - - public void setLastKnot(float x, float y) - { - lastKnot.setLocation(x, y); - } -// public void setPoint(float x, float y) -// { -// history[0].setLocation(x, y); -// length = 1; -// } -// public void setStart(float x, float y) -// { -// start.setLocation(x, y); -// } -// public void setPointAndKnot(float x, float y, float kx, float ky) -// { -// history[0].setLocation(x, y); -// history[1].setLocation(kx, ky); -// length = 2; -// } -} --- a/src/com/kitfox/svg/pathcmd/Cubic.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on January 26, 2004, 8:40 PM - */ - -package com.kitfox.svg.pathcmd; - -//import org.apache.batik.ext.awt.geom.ExtendedGeneralPath; -import java.awt.geom.*; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class Cubic extends PathCommand { - - public float k1x = 0f; - public float k1y = 0f; - public float k2x = 0f; - public float k2y = 0f; - public float x = 0f; - public float y = 0f; - - /** Creates a new instance of MoveTo */ - public Cubic() { - } - - @Override - public String toString() - { - return "C " + k1x + " " + k1y - + " " + k2x + " " + k2y - + " " + x + " " + y; - } - - public Cubic(boolean isRelative, float k1x, float k1y, float k2x, float k2y, float x, float y) { - super(isRelative); - this.k1x = k1x; - this.k1y = k1y; - this.k2x = k2x; - this.k2y = k2y; - this.x = x; - this.y = y; - } - -// public void appendPath(ExtendedGeneralPath path, BuildHistory hist) - @Override - public void appendPath(GeneralPath path, BuildHistory hist) - { - float offx = isRelative ? hist.lastPoint.x : 0f; - float offy = isRelative ? hist.lastPoint.y : 0f; - - path.curveTo(k1x + offx, k1y + offy, - k2x + offx, k2y + offy, - x + offx, y + offy); -// hist.setPointAndKnot(x + offx, y + offy, k2x + offx, k2y + offy); - hist.setLastPoint(x + offx, y + offy); - hist.setLastKnot(k2x + offx, k2y + offy); - } - - @Override - public int getNumKnotsAdded() - { - return 6; - } -} --- a/src/com/kitfox/svg/pathcmd/CubicSmooth.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on January 26, 2004, 8:40 PM - */ - -package com.kitfox.svg.pathcmd; - -//import org.apache.batik.ext.awt.geom.ExtendedGeneralPath; -import java.awt.geom.*; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class CubicSmooth extends PathCommand { - - public float x = 0f; - public float y = 0f; - public float k2x = 0f; - public float k2y = 0f; - - /** Creates a new instance of MoveTo */ - public CubicSmooth() { - } - - public CubicSmooth(boolean isRelative, float k2x, float k2y, float x, float y) { - super(isRelative); - this.k2x = k2x; - this.k2y = k2y; - this.x = x; - this.y = y; - } - -// public void appendPath(ExtendedGeneralPath path, BuildHistory hist) - @Override - public void appendPath(GeneralPath path, BuildHistory hist) - { - float offx = isRelative ? hist.lastPoint.x : 0f; - float offy = isRelative ? hist.lastPoint.y : 0f; - - float oldKx = hist.lastKnot.x; - float oldKy = hist.lastKnot.y; - float oldX = hist.lastPoint.x; - float oldY = hist.lastPoint.y; - //Calc knot as reflection of old knot - float k1x = oldX * 2f - oldKx; - float k1y = oldY * 2f - oldKy; - - path.curveTo(k1x, k1y, k2x + offx, k2y + offy, x + offx, y + offy); - hist.setLastPoint(x + offx, y + offy); - hist.setLastKnot(k2x + offx, k2y + offy); - } - - @Override - public int getNumKnotsAdded() - { - return 6; - } - - @Override - public String toString() - { - return "S " + k2x + " " + k2y - + " " + x + " " + y; - } -} --- a/src/com/kitfox/svg/pathcmd/Horizontal.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on January 26, 2004, 8:40 PM - */ - -package com.kitfox.svg.pathcmd; - -//import org.apache.batik.ext.awt.geom.ExtendedGeneralPath; -import java.awt.geom.*; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class Horizontal extends PathCommand { - - public float x = 0f; - - /** Creates a new instance of MoveTo */ - public Horizontal() { - } - - @Override - public String toString() - { - return "H " + x; - } - - public Horizontal(boolean isRelative, float x) { - super(isRelative); - this.x = x; - } - - -// public void appendPath(ExtendedGeneralPath path, BuildHistory hist) - @Override - public void appendPath(GeneralPath path, BuildHistory hist) - { - float offx = isRelative ? hist.lastPoint.x : 0f; - float offy = hist.lastPoint.y; - - path.lineTo(x + offx, offy); - hist.setLastPoint(x + offx, offy); - hist.setLastKnot(x + offx, offy); - } - - @Override - public int getNumKnotsAdded() - { - return 2; - } -} --- a/src/com/kitfox/svg/pathcmd/LineTo.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on January 26, 2004, 8:40 PM - */ - -package com.kitfox.svg.pathcmd; - -//import org.apache.batik.ext.awt.geom.ExtendedGeneralPath; -import java.awt.geom.*; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class LineTo extends PathCommand { - - public float x = 0f; - public float y = 0f; - - /** Creates a new instance of MoveTo */ - public LineTo() { - } - - public LineTo(boolean isRelative, float x, float y) { - super(isRelative); - this.x = x; - this.y = y; - } - - -// public void appendPath(ExtendedGeneralPath path, BuildHistory hist) - @Override - public void appendPath(GeneralPath path, BuildHistory hist) - { - float offx = isRelative ? hist.lastPoint.x : 0f; - float offy = isRelative ? hist.lastPoint.y : 0f; - - path.lineTo(x + offx, y + offy); - hist.setLastPoint(x + offx, y + offy); - hist.setLastKnot(x + offx, y + offy); - } - - @Override - public int getNumKnotsAdded() - { - return 2; - } - - @Override - public String toString() - { - return "L " + x + " " + y; - } -} --- a/src/com/kitfox/svg/pathcmd/MoveTo.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on January 26, 2004, 8:40 PM - */ - -package com.kitfox.svg.pathcmd; - -//import org.apache.batik.ext.awt.geom.ExtendedGeneralPath; -import java.awt.geom.*; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class MoveTo extends PathCommand { - - public float x = 0f; - public float y = 0f; - - /** Creates a new instance of MoveTo */ - public MoveTo() { - } - - public MoveTo(boolean isRelative, float x, float y) { - super(isRelative); - this.x = x; - this.y = y; - } - -// public void appendPath(ExtendedGeneralPath path, BuildHistory hist) - @Override - public void appendPath(GeneralPath path, BuildHistory hist) - { - float offx = isRelative ? hist.lastPoint.x : 0f; - float offy = isRelative ? hist.lastPoint.y : 0f; - - path.moveTo(x + offx, y + offy); - hist.setStartPoint(x + offx, y + offy); - hist.setLastPoint(x + offx, y + offy); - hist.setLastKnot(x + offx, y + offy); - } - - @Override - public int getNumKnotsAdded() - { - return 2; - } - - @Override - public String toString() - { - return "M " + x + " " + y; - } - - -} --- a/src/com/kitfox/svg/pathcmd/PathCommand.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on January 26, 2004, 8:39 PM - */ - -package com.kitfox.svg.pathcmd; - -//import org.apache.batik.ext.awt.geom.ExtendedGeneralPath; -import java.awt.geom.*; - -/** - * This is the element of a path and contains instructions for rendering a - * portion of the path - * - * @author Mark McKay - * @author Mark McKay - */ -abstract public class PathCommand { - - public boolean isRelative = false; - - /** Creates a new instance of PathCommand */ - public PathCommand() { - } - - public PathCommand(boolean isRelative) { - this.isRelative = isRelative; - } - -// abstract public void appendPath(ExtendedGeneralPath path, BuildHistory hist); - abstract public void appendPath(GeneralPath path, BuildHistory hist); - - abstract public int getNumKnotsAdded(); -} --- a/src/com/kitfox/svg/pathcmd/PathParser.java +++ /dev/null @@ -1,251 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - */ -package com.kitfox.svg.pathcmd; - -import java.util.ArrayList; -import java.util.List; - -/** - * A helper for parsing {@link PathCommand}s. - * - * @author Jannis Weis - */ -public class PathParser -{ - private final String input; - private final int inputLength; - private int index; - private char currentCommand; - - public PathParser(String input) { - this.input = input.trim(); - this.inputLength = this.input.length(); - } - - private boolean isCommandChar(char c) - { - return c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z'; - } - - private boolean isWhiteSpaceOrSeparator(char c) - { - return c <= ' ' || c == ','; - } - - private char peek() - { - return input.charAt(index); - } - - private void consume() - { - index++; - } - - private boolean hasNext() - { - return index < inputLength; - } - - // This only checks for the rough structure of a number as we need to know - // when to separate the next token. - // Explicit parsing is done by Float#parseFloat. - private boolean isValidNumberChar(char c, NumberCharState state) - { - boolean valid = '0' <= c && c <= '9'; - if (valid && state.iteration == 1 && input.charAt(index - 1) == '0') - { - // Break up combined zeros into multiple numbers. - return false; - } - state.signAllowed = state.signAllowed && !valid; - if (state.dotAllowed && !valid) - { - valid = c == '.'; - state.dotAllowed = !valid; - } - if (state.signAllowed && !valid) - { - valid = c == '+' || c == '-'; - state.signAllowed = valid; - } - if (state.exponentAllowed && !valid) - { - // Possible exponent notation. Needs at least one preceding number - valid = c == 'e' || c == 'E'; - state.exponentAllowed = !valid; - state.signAllowed = valid; - } - state.iteration++; - return valid; - } - - private void consumeWhiteSpaceOrSeparator() { - while (hasNext() && isWhiteSpaceOrSeparator(peek())) { - consume(); - } - } - - private float nextFloat() - { - int start = index; - NumberCharState state = new NumberCharState(); - while (hasNext() && isValidNumberChar(peek(), state)) { - consume(); - } - int end = index; - consumeWhiteSpaceOrSeparator(); - String token = input.substring(start, end); - try - { - return Float.parseFloat(token); - } catch (NumberFormatException e) - { - String msg = "Unexpected element while parsing cmd '" + currentCommand - + "' encountered token '" + token + "' rest=" + input.substring(start, Math.min(input.length(), start + 10)) - + " (index=" + index + " in input=" + input + ")"; - throw new IllegalStateException(msg, e); - } - } - - public PathCommand[] parsePathCommand() - { - List commands = new ArrayList<>(); - - currentCommand = 'Z'; - while (hasNext()) - { - char peekChar = peek(); - if (isCommandChar(peekChar)) - { - consume(); - currentCommand = peekChar; - } - consumeWhiteSpaceOrSeparator(); - - PathCommand cmd; - switch (currentCommand) - { - case 'M': - cmd = new MoveTo(false, nextFloat(), nextFloat()); - currentCommand = 'L'; - break; - case 'm': - cmd = new MoveTo(true, nextFloat(), nextFloat()); - currentCommand = 'l'; - break; - case 'L': - cmd = new LineTo(false, nextFloat(), nextFloat()); - break; - case 'l': - cmd = new LineTo(true, nextFloat(), nextFloat()); - break; - case 'H': - cmd = new Horizontal(false, nextFloat()); - break; - case 'h': - cmd = new Horizontal(true, nextFloat()); - break; - case 'V': - cmd = new Vertical(false, nextFloat()); - break; - case 'v': - cmd = new Vertical(true, nextFloat()); - break; - case 'A': - cmd = new Arc(false, nextFloat(), nextFloat(), - nextFloat(), - nextFloat() == 1f, nextFloat() == 1f, - nextFloat(), nextFloat()); - break; - case 'a': - cmd = new Arc(true, nextFloat(), nextFloat(), - nextFloat(), - nextFloat() == 1f, nextFloat() == 1f, - nextFloat(), nextFloat()); - break; - case 'Q': - cmd = new Quadratic(false, nextFloat(), nextFloat(), - nextFloat(), nextFloat()); - break; - case 'q': - cmd = new Quadratic(true, nextFloat(), nextFloat(), - nextFloat(), nextFloat()); - break; - case 'T': - cmd = new QuadraticSmooth(false, nextFloat(), nextFloat()); - break; - case 't': - cmd = new QuadraticSmooth(true, nextFloat(), nextFloat()); - break; - case 'C': - cmd = new Cubic(false, nextFloat(), nextFloat(), - nextFloat(), nextFloat(), - nextFloat(), nextFloat()); - break; - case 'c': - cmd = new Cubic(true, nextFloat(), nextFloat(), - nextFloat(), nextFloat(), - nextFloat(), nextFloat()); - break; - case 'S': - cmd = new CubicSmooth(false, nextFloat(), nextFloat(), - nextFloat(), nextFloat()); - break; - case 's': - cmd = new CubicSmooth(true, nextFloat(), nextFloat(), - nextFloat(), nextFloat()); - break; - case 'Z': - case 'z': - cmd = new Terminal(); - break; - default: - throw new RuntimeException("Invalid path element " - + currentCommand + "(at index=" + index + " in input=" + input + ")"); - } - commands.add(cmd); - } - return commands.toArray(new PathCommand[0]); - } - - private static class NumberCharState - { - int iteration = 0; - boolean dotAllowed = true; - boolean signAllowed = true; - boolean exponentAllowed = true; - } -} --- a/src/com/kitfox/svg/pathcmd/PathUtil.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on May 10, 2005, 5:56 AM - */ - -package com.kitfox.svg.pathcmd; - -import java.awt.geom.*; - -/** - * - * @author kitfox - */ -public class PathUtil -{ - - /** Creates a new instance of PathUtil */ - public PathUtil() - { - } - - /** - * Converts a GeneralPath into an SVG representation - * - * @param path The shape to be encoded - * @return A string encoding the path using the SVG path notation - */ - public static String buildPathString(GeneralPath path) - { - float[] coords = new float[6]; - - StringBuffer sb = new StringBuffer(); - - for (PathIterator pathIt = path.getPathIterator(new AffineTransform()); !pathIt.isDone(); pathIt.next()) - { - int segId = pathIt.currentSegment(coords); - - switch (segId) - { - case PathIterator.SEG_CLOSE: - { - sb.append(" Z"); - break; - } - case PathIterator.SEG_CUBICTO: - { - sb.append(" C " + coords[0] + " " + coords[1] + " " + coords[2] + " " + coords[3] + " " + coords[4] + " " + coords[5]); - break; - } - case PathIterator.SEG_LINETO: - { - sb.append(" L " + coords[0] + " " + coords[1]); - break; - } - case PathIterator.SEG_MOVETO: - { - sb.append(" M " + coords[0] + " " + coords[1]); - break; - } - case PathIterator.SEG_QUADTO: - { - sb.append(" Q " + coords[0] + " " + coords[1] + " " + coords[2] + " " + coords[3]); - break; - } - } - } - - return sb.toString(); - } -} --- a/src/com/kitfox/svg/pathcmd/Quadratic.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on January 26, 2004, 8:40 PM - */ - -package com.kitfox.svg.pathcmd; - -//import org.apache.batik.ext.awt.geom.ExtendedGeneralPath; -import java.awt.geom.*; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class Quadratic extends PathCommand { - - public float kx = 0f; - public float ky = 0f; - public float x = 0f; - public float y = 0f; - - /** Creates a new instance of MoveTo */ - public Quadratic() { - } - - @Override - public String toString() - { - return "Q " + kx + " " + ky - + " " + x + " " + y; - } - - public Quadratic(boolean isRelative, float kx, float ky, float x, float y) { - super(isRelative); - this.kx = kx; - this.ky = ky; - this.x = x; - this.y = y; - } - -// public void appendPath(ExtendedGeneralPath path, BuildHistory hist) - @Override - public void appendPath(GeneralPath path, BuildHistory hist) - { - float offx = isRelative ? hist.lastPoint.x : 0f; - float offy = isRelative ? hist.lastPoint.y : 0f; - - path.quadTo(kx + offx, ky + offy, x + offx, y + offy); - hist.setLastPoint(x + offx, y + offy); - hist.setLastKnot(kx + offx, ky + offy); - } - - @Override - public int getNumKnotsAdded() - { - return 4; - } -} --- a/src/com/kitfox/svg/pathcmd/QuadraticSmooth.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on January 26, 2004, 8:40 PM - */ - -package com.kitfox.svg.pathcmd; - -//import org.apache.batik.ext.awt.geom.ExtendedGeneralPath; -import java.awt.geom.*; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class QuadraticSmooth extends PathCommand { - - public float x = 0f; - public float y = 0f; - - /** Creates a new instance of MoveTo */ - public QuadraticSmooth() { - } - - @Override - public String toString() - { - return "T " + x + " " + y; - } - - public QuadraticSmooth(boolean isRelative, float x, float y) { - super(isRelative); - this.x = x; - this.y = y; - } - -// public void appendPath(ExtendedGeneralPath path, BuildHistory hist) - @Override - public void appendPath(GeneralPath path, BuildHistory hist) - { - float offx = isRelative ? hist.lastPoint.x : 0f; - float offy = isRelative ? hist.lastPoint.y : 0f; - - float oldKx = hist.lastKnot.x; - float oldKy = hist.lastKnot.y; - float oldX = hist.lastPoint.x; - float oldY = hist.lastPoint.y; - //Calc knot as reflection of old knot - float kx = oldX * 2f - oldKx; - float ky = oldY * 2f - oldKy; - - path.quadTo(kx, ky, x + offx, y + offy); - hist.setLastPoint(x + offx, y + offy); - hist.setLastKnot(kx, ky); - } - - @Override - public int getNumKnotsAdded() - { - return 4; - } -} --- a/src/com/kitfox/svg/pathcmd/Terminal.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on January 26, 2004, 8:40 PM - */ - -package com.kitfox.svg.pathcmd; - -//import org.apache.batik.ext.awt.geom.ExtendedGeneralPath; -import java.awt.geom.*; - -/** - * Finishes a path - * - * @author Mark McKay - * @author Mark McKay - */ -public class Terminal extends PathCommand { - - /** Creates a new instance of MoveTo */ - public Terminal() { - } - - @Override - public String toString() - { - return "Z"; - } - - -// public void appendPath(ExtendedGeneralPath path, BuildHistory hist) - @Override - public void appendPath(GeneralPath path, BuildHistory hist) - { - path.closePath(); - hist.setLastPoint(hist.startPoint.x, hist.startPoint.y); - hist.setLastKnot(hist.startPoint.x, hist.startPoint.y); - } - - @Override - public int getNumKnotsAdded() - { - return 0; - } -} --- a/src/com/kitfox/svg/pathcmd/Vertical.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on January 26, 2004, 8:40 PM - */ - -package com.kitfox.svg.pathcmd; - -//import org.apache.batik.ext.awt.geom.ExtendedGeneralPath; -import java.awt.geom.*; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class Vertical extends PathCommand { - - public float y = 0f; - - /** Creates a new instance of MoveTo */ - public Vertical() { - } - - @Override - public String toString() - { - return "V " + y; - } - - public Vertical(boolean isRelative, float y) { - super(isRelative); - this.y = y; - } - -// public void appendPath(ExtendedGeneralPath path, BuildHistory hist) - @Override - public void appendPath(GeneralPath path, BuildHistory hist) - { - float offx = hist.lastPoint.x; - float offy = isRelative ? hist.lastPoint.y : 0f; - - path.lineTo(offx, y + offy); - hist.setLastPoint(offx, y + offy); - hist.setLastKnot(offx, y + offy); - } - - @Override - public int getNumKnotsAdded() - { - return 2; - } -} --- a/src/com/kitfox/svg/pattern/PatternPaint.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on April 1, 2004, 3:37 AM - */ - -package com.kitfox.svg.pattern; - -import java.awt.*; -import java.awt.geom.*; -import java.awt.image.*; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class PatternPaint implements Paint -{ - BufferedImage source; //Image we're rendering from - AffineTransform xform; - - /** Creates a new instance of PatternPaint */ - public PatternPaint(BufferedImage source, AffineTransform xform) - { - this.source = source; - this.xform = xform; - } - - public PaintContext createContext(ColorModel cm, Rectangle deviceBounds, Rectangle2D userBounds, AffineTransform xform, RenderingHints hints) - { - return new PatternPaintContext(source, deviceBounds, xform, this.xform); - } - - public int getTransparency() - { - return source.getColorModel().getTransparency(); - } - -} --- a/src/com/kitfox/svg/pattern/PatternPaintContext.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on April 1, 2004, 3:37 AM - */ - -package com.kitfox.svg.pattern; - -import com.kitfox.svg.SVGConst; -import java.awt.*; -import java.awt.geom.*; -import java.awt.image.*; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class PatternPaintContext implements PaintContext -{ - BufferedImage source; //Image we're rendering from - Rectangle deviceBounds; //int size of rectangle we're rendering to -// AffineTransform userXform; //xform from user space to device space -// AffineTransform distortXform; //distortion applied to this pattern - - AffineTransform xform; //distortion applied to this pattern - - int sourceWidth; - int sourceHeight; - - //Raster we use to build tile - BufferedImage buf; - - /** Creates a new instance of PatternPaintContext */ - public PatternPaintContext(BufferedImage source, Rectangle deviceBounds, AffineTransform userXform, AffineTransform distortXform) - { -//System.err.println("Bounds " + deviceBounds); - this.source = source; - this.deviceBounds = deviceBounds; - try { -// this.distortXform = distortXform.createInverse(); -// this.userXform = userXform.createInverse(); - -// xform = userXform.createInverse(); -// xform.concatenate(distortXform.createInverse()); - xform = distortXform.createInverse(); - xform.concatenate(userXform.createInverse()); - } - catch (Exception e) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, null, e); - } - - sourceWidth = source.getWidth(); - sourceHeight = source.getHeight(); - } - - public void dispose() { - } - - public ColorModel getColorModel() { - return source.getColorModel(); - } - - public Raster getRaster(int x, int y, int w, int h) - { -//System.err.println("" + x + ", " + y + ", " + w + ", " + h); - if (buf == null || buf.getWidth() != w || buf.getHeight() != h) - { - buf = new BufferedImage(w, h, source.getType()); - } - -// Point2D.Float srcPt = new Point2D.Float(), srcPt2 = new Point2D.Float(), destPt = new Point2D.Float(); - Point2D.Float srcPt = new Point2D.Float(), destPt = new Point2D.Float(); - for (int j = 0; j < h; j++) - { - for (int i = 0; i < w; i++) - { - destPt.setLocation(i + x, j + y); - - xform.transform(destPt, srcPt); - -// userXform.transform(destPt, srcPt2); -// distortXform.transform(srcPt2, srcPt); - - int ii = ((int)srcPt.x) % sourceWidth; - if (ii < 0) ii += sourceWidth; - int jj = ((int)srcPt.y) % sourceHeight; - if (jj < 0) jj += sourceHeight; - - buf.setRGB(i, j, source.getRGB(ii, jj)); - } - } - - return buf.getData(); - } - - public static void main(String[] argv) - { - int i = -4; - System.err.println("Hello " + (i % 4)); - } - -} --- a/src/com/kitfox/svg/util/Base64Consts.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on July 23, 2007 - */ - -package com.kitfox.svg.util; - -/** - * - * @author kitfox - */ -public interface Base64Consts -{ - final String BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - - -} --- a/src/com/kitfox/svg/util/Base64InputStream.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on July 23, 2007 - */ - -package com.kitfox.svg.util; - -import java.io.FilterInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.HashMap; - -/** - * - * @author kitfox - */ -public class Base64InputStream extends FilterInputStream implements Base64Consts -{ - static final HashMap lookup64 = new HashMap(); - static { - byte[] ch = BASE64_CHARS.getBytes(); - for (int i = 0; i < ch.length; i++) - { - lookup64.put(new Byte(ch[i]), new Integer(i)); - } - } - - int buf; - int charsInBuf; - - /** Creates a new instance of Base64InputStream */ - public Base64InputStream(InputStream in) - { - super(in); - } - - @Override - public int read(byte[] b, int off, int len) throws IOException - { - for (int i = 0; i < len; ++i) - { - int val = read(); - if (val == -1) - { - return i == 0 ? -1 : i; - } - b[off + i] = (byte)val; - } - return len; - } - - - @Override - public int read() throws IOException - { - if (charsInBuf == 0) - { - fillBuffer(); - if (charsInBuf == 0) - { - return -1; - } - } - - return (buf >> (--charsInBuf * 8)) & 0xff; - } - - private void fillBuffer() throws IOException - { - //Read next 4 characters - int bitsRead = 0; - while (bitsRead < 24) - { - int val = in.read(); - if (val == -1 || val == '=') break; - - Integer lval = (Integer)lookup64.get(new Byte((byte)val)); - if (lval == null) continue; - - buf = buf << 6 | lval.byteValue(); - bitsRead += 6; - } - - switch (bitsRead) - { - case 6: - { - throw new RuntimeException("Invalid termination of base64 encoding."); - } - case 12: - { - buf >>= 4; - bitsRead = 8; - break; - } - case 18: - { - buf >>= 2; - bitsRead = 16; - break; - } - case 0: - case 24: - { - break; - } - default: - { - assert false : "Should never encounter other bit counts"; - } - } - - charsInBuf = bitsRead / 8; - } -} --- a/src/com/kitfox/svg/util/Base64OutputStream.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on July 23, 2007 - */ - -package com.kitfox.svg.util; - -import java.io.FilterOutputStream; -import java.io.IOException; -import java.io.OutputStream; - -/** - * - * @author kitfox - */ -public class Base64OutputStream extends FilterOutputStream implements Base64Consts -{ - int buf; - int bitsUsed; - int charsPrinted; - - /** Creates a new instance of Base64OutputSream */ - public Base64OutputStream(OutputStream out) - { - super(out); - } - - @Override - public void close() throws IOException - { - writeBits(); - super.close(); - } - - @Override - public void write(int b) throws IOException - { - buf = buf << 8 | (b & 0xff); - bitsUsed += 8; - if (bitsUsed == 24) - { - writeBits(); - } - } - - private void writeBits() throws IOException - { - int padSize; - //Pad unused bits with 0 - switch (bitsUsed) - { - case 8: - { - bitsUsed = 12; - buf <<= 4; - padSize = 2; - break; - } - case 16: - { - bitsUsed = 18; - buf <<= 2; - padSize = 1; - break; - } - default: - { - padSize = 0; - break; - } - } - - if (charsPrinted == 76) - { - out.write('\r'); - out.write('\n'); - charsPrinted = 0; - } - - for (; bitsUsed > 0; bitsUsed -= 6) - { - int b = buf >> (bitsUsed - 6) & 0x3f; - out.write(BASE64_CHARS.charAt(b)); - } - - for (int i = 0; i < padSize; i++) - { - out.write('='); - } - - charsPrinted += 4; - } -} --- a/src/com/kitfox/svg/util/FontSystem.java +++ /dev/null @@ -1,170 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on April 24, 2015 - */ -package com.kitfox.svg.util; - -import com.kitfox.svg.Font; -import com.kitfox.svg.FontFace; -import com.kitfox.svg.Glyph; -import com.kitfox.svg.MissingGlyph; - -import java.awt.GraphicsEnvironment; -import java.awt.font.FontRenderContext; -import java.awt.font.GlyphMetrics; -import java.awt.font.GlyphVector; -import java.awt.font.LineMetrics; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Locale; - -/** - * - * @author kitfox - */ -public class FontSystem extends Font -{ - java.awt.Font sysFont; - - HashMap glyphCache = new HashMap<>(); - - static HashSet sysFontNames = new HashSet<>(); - - public static boolean checkIfSystemFontExists(String fontName) - { - if (sysFontNames.isEmpty()) - { - for (String name: GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames(Locale.ENGLISH)) - { - sysFontNames.add(name); - } - } - - return sysFontNames.contains(fontName); - } - - public static FontSystem createFont(String[] fontFamilies, int fontStyle, int fontWeight, float fontSize) - { - for (String fontName: fontFamilies) - { - String javaFontName = mapJavaFontName(fontName); - if (checkIfSystemFontExists(javaFontName)) - { - return new FontSystem(javaFontName, fontStyle, fontWeight, fontSize); - } - } - - return null; - } - - private static String mapJavaFontName(String fontName) - { - if ("serif".equals(fontName)) - { - return java.awt.Font.SERIF; - } - else if ("sans-serif".equals(fontName)) - { - return java.awt.Font.SANS_SERIF; - } - else if ("monospace".equals(fontName)) - { - return java.awt.Font.MONOSPACED; - } - return fontName; - } - - private FontSystem(String fontFamily, int fontStyle, int fontWeight, float fontSize) - { - int style; - switch (fontStyle) - { - case com.kitfox.svg.Text.TXST_ITALIC: - style = java.awt.Font.ITALIC; - break; - default: - style = java.awt.Font.PLAIN; - break; - } - - int weight; - switch (fontWeight) - { - case com.kitfox.svg.Text.TXWE_BOLD: - case com.kitfox.svg.Text.TXWE_BOLDER: - weight = java.awt.Font.BOLD; - break; - default: - weight = java.awt.Font.PLAIN; - break; - } - - sysFont = new java.awt.Font(fontFamily, style | weight, 1).deriveFont(fontSize); - - FontRenderContext fontRenderContext = new FontRenderContext(null, true, true); - LineMetrics lineMetrics = sysFont.getLineMetrics("M", fontRenderContext); - - FontFace face = new FontFace(); - face.setAscent((int) lineMetrics.getAscent()); - face.setDescent((int) lineMetrics.getDescent()); - face.setUnitsPerEm((int) sysFont.getStringBounds("M", fontRenderContext).getWidth()); - setFontFace(face); - } - - @Override - public MissingGlyph getGlyph(String unicode) - { - FontRenderContext frc = new FontRenderContext(null, true, true); - GlyphVector vec = sysFont.createGlyphVector(frc, unicode); - - Glyph glyph = (Glyph)glyphCache.get(unicode); - if (glyph == null) - { - glyph = new Glyph(); - glyph.setPath(vec.getGlyphOutline(0)); - - GlyphMetrics gm = vec.getGlyphMetrics(0); - glyph.setHorizAdvX(gm.getAdvanceX()); - glyph.setVertAdvY(gm.getAdvanceY()); - glyph.setVertOriginX(0); - glyph.setVertOriginY(0); - - glyphCache.put(unicode, glyph); - } - - return glyph; - } - - -} --- a/src/com/kitfox/svg/util/FontUtil.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - */ -package com.kitfox.svg.util; - -import com.kitfox.svg.Font; -import com.kitfox.svg.SVGDiagram; -import com.kitfox.svg.SVGElement; -import com.kitfox.svg.SVGException; -import com.kitfox.svg.Text; -import com.kitfox.svg.xml.StyleAttribute; - -import java.util.Arrays; -import java.util.Objects; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * Utility class for parsing font information of an {@link SVGElement}. - * - * @author Jannis Weis - */ -public final class FontUtil -{ - - private static final String DEFAULT_FONT_FAMILY = "sans-serif"; - private static final float DEFAULT_FONT_SIZE = 12f; - private static final int DEFAULT_LETTER_SPACING = 0; - private static final int DEFAULT_FONT_STYLE = Text.TXST_NORMAL; - private static final int DEFAULT_FONT_WEIGHT = Text.TXWE_NORMAL; - - private FontUtil() {} - - public final static class FontInfo { - public final String[] families; - public final float size; - public final int style; - public final int weight; - public final float letterSpacing; - - public FontInfo(String[] families, float size, int style, int weight, float letterSpacing) - { - this.families = families; - this.size = size; - this.style = style; - this.weight = weight; - this.letterSpacing = letterSpacing; - } - - @Override - public boolean equals(Object o) - { - if (this == o) return true; - if (!(o instanceof FontInfo)) return false; - FontInfo fontInfo = (FontInfo) o; - return Float.compare(fontInfo.size, size) == 0 - && style == fontInfo.style && weight == fontInfo.weight - && Float.compare(fontInfo.letterSpacing, letterSpacing) == 0 - && Arrays.equals(families, fontInfo.families); - } - - @Override - public int hashCode() - { - int result = Objects.hash(size, style, weight, letterSpacing); - result = 31 * result + Arrays.hashCode(families); - return result; - } - } - - public static FontInfo parseFontInfo(SVGElement element, StyleAttribute sty) throws SVGException - { - String fontFamily = DEFAULT_FONT_FAMILY; - if (element.getStyle(sty.setName("font-family"))) - { - fontFamily = sty.getStringValue(); - } - - float fontSize = DEFAULT_FONT_SIZE; - if (element.getStyle(sty.setName("font-size"))) - { - fontSize = sty.getFloatValueWithUnits(); - } - - float letterSpacing = DEFAULT_LETTER_SPACING; - if (element.getStyle(sty.setName("letter-spacing"))) - { - letterSpacing = sty.getFloatValueWithUnits(); - } - - int fontStyle = DEFAULT_FONT_STYLE; - if (element.getStyle(sty.setName("font-style"))) - { - String s = sty.getStringValue(); - if ("normal".equals(s)) - { - fontStyle = Text.TXST_NORMAL; - } else if ("italic".equals(s)) - { - fontStyle = Text.TXST_ITALIC; - } else if ("oblique".equals(s)) - { - fontStyle = Text.TXST_OBLIQUE; - } - } - - int fontWeight = DEFAULT_FONT_WEIGHT; - if (element.getStyle(sty.setName("font-weight"))) - { - String s = sty.getStringValue(); - if ("normal".equals(s)) - { - fontWeight = Text.TXWE_NORMAL; - } else if ("bold".equals(s)) - { - fontWeight = Text.TXWE_BOLD; - } - } - - return new FontInfo(fontFamily.split(","), fontSize, fontStyle, fontWeight, letterSpacing); - } - - public static Font getFont(FontInfo info, SVGDiagram diagram) - { - return getFont(info.families, info.style, info.weight, info.size, diagram); - } - - private static Font getFont(String[] families, int fontStyle, int fontWeight, float fontSize, SVGDiagram diagram) - { - Font font = null; - for (String family : families) - { - font = diagram.getUniverse().getFont(family); - if (font != null) break; - } - if (font == null) - { - //Check system fonts - font = FontSystem.createFont(families, fontStyle, fontWeight, fontSize); - } - if (font == null) - { - Logger.getLogger(FontSystem.class.getName()) - .log(Level.WARNING, "Could not create font " + Arrays.toString(families)); - String[] defaultFont = new String[]{ FontUtil.DEFAULT_FONT_FAMILY }; - font = FontSystem.createFont(defaultFont, fontStyle, fontWeight, fontSize); - } - return font; - } - -} --- a/src/com/kitfox/svg/util/TextBuilder.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on April 24, 2015 - */ -package com.kitfox.svg.util; - -/** - * - * @author kitfox - */ -public class TextBuilder -{ - -} --- a/src/com/kitfox/svg/xml/ColorTable.java +++ /dev/null @@ -1,294 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on January 26, 2004, 4:34 AM - */ - -package com.kitfox.svg.xml; - -import java.awt.*; -import java.util.*; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class ColorTable -{ - - static final Map colorTable; - static { - HashMap table = new HashMap(); - - //We really should be interpreting the currentColor keyword as - // a reference to the referring node's color, but this quick hack - // will stop the program from crashing. - table.put("currentcolor", new Color(0x0)); - - table.put("aliceblue", new Color(0xf0f8ff)); - table.put("antiquewhite", new Color(0xfaebd7)); - table.put("aqua", new Color(0x00ffff)); - table.put("aquamarine", new Color(0x7fffd4)); - table.put("azure", new Color(0xf0ffff)); - table.put("beige", new Color(0xf5f5dc)); - table.put("bisque", new Color(0xffe4c4)); - table.put("black", new Color(0x000000)); - table.put("blanchedalmond", new Color(0xffebcd)); - table.put("blue", new Color(0x0000ff)); - table.put("blueviolet", new Color(0x8a2be2)); - table.put("brown", new Color(0xa52a2a)); - table.put("burlywood", new Color(0xdeb887)); - table.put("cadetblue", new Color(0x5f9ea0)); - table.put("chartreuse", new Color(0x7fff00)); - table.put("chocolate", new Color(0xd2691e)); - table.put("coral", new Color(0xff7f50)); - table.put("cornflowerblue", new Color(0x6495ed)); - table.put("cornsilk", new Color(0xfff8dc)); - table.put("crimson", new Color(0xdc143c)); - table.put("cyan", new Color(0x00ffff)); - table.put("darkblue", new Color(0x00008b)); - table.put("darkcyan", new Color(0x008b8b)); - table.put("darkgoldenrod", new Color(0xb8860b)); - table.put("darkgray", new Color(0xa9a9a9)); - table.put("darkgreen", new Color(0x006400)); - table.put("darkkhaki", new Color(0xbdb76b)); - table.put("darkmagenta", new Color(0x8b008b)); - table.put("darkolivegreen", new Color(0x556b2f)); - table.put("darkorange", new Color(0xff8c00)); - table.put("darkorchid", new Color(0x9932cc)); - table.put("darkred", new Color(0x8b0000)); - table.put("darksalmon", new Color(0xe9967a)); - table.put("darkseagreen", new Color(0x8fbc8f)); - table.put("darkslateblue", new Color(0x483d8b)); - table.put("darkslategray", new Color(0x2f4f4f)); - table.put("darkturquoise", new Color(0x00ced1)); - table.put("darkviolet", new Color(0x9400d3)); - table.put("deeppink", new Color(0xff1493)); - table.put("deepskyblue", new Color(0x00bfff)); - table.put("dimgray", new Color(0x696969)); - table.put("dodgerblue", new Color(0x1e90ff)); - table.put("feldspar", new Color(0xd19275)); - table.put("firebrick", new Color(0xb22222)); - table.put("floralwhite", new Color(0xfffaf0)); - table.put("forestgreen", new Color(0x228b22)); - table.put("fuchsia", new Color(0xff00ff)); - table.put("gainsboro", new Color(0xdcdcdc)); - table.put("ghostwhite", new Color(0xf8f8ff)); - table.put("gold", new Color(0xffd700)); - table.put("goldenrod", new Color(0xdaa520)); - table.put("gray", new Color(0x808080)); - table.put("green", new Color(0x008000)); - table.put("greenyellow", new Color(0xadff2f)); - table.put("honeydew", new Color(0xf0fff0)); - table.put("hotpink", new Color(0xff69b4)); - table.put("indianred", new Color(0xcd5c5c)); - table.put("indigo", new Color(0x4b0082)); - table.put("ivory", new Color(0xfffff0)); - table.put("khaki", new Color(0xf0e68c)); - table.put("lavender", new Color(0xe6e6fa)); - table.put("lavenderblush", new Color(0xfff0f5)); - table.put("lawngreen", new Color(0x7cfc00)); - table.put("lemonchiffon", new Color(0xfffacd)); - table.put("lightblue", new Color(0xadd8e6)); - table.put("lightcoral", new Color(0xf08080)); - table.put("lightcyan", new Color(0xe0ffff)); - table.put("lightgoldenrodyellow", new Color(0xfafad2)); - table.put("lightgrey", new Color(0xd3d3d3)); - table.put("lightgreen", new Color(0x90ee90)); - table.put("lightpink", new Color(0xffb6c1)); - table.put("lightsalmon", new Color(0xffa07a)); - table.put("lightseagreen", new Color(0x20b2aa)); - table.put("lightskyblue", new Color(0x87cefa)); - table.put("lightslateblue", new Color(0x8470ff)); - table.put("lightslategray", new Color(0x778899)); - table.put("lightsteelblue", new Color(0xb0c4de)); - table.put("lightyellow", new Color(0xffffe0)); - table.put("lime", new Color(0x00ff00)); - table.put("limegreen", new Color(0x32cd32)); - table.put("linen", new Color(0xfaf0e6)); - table.put("magenta", new Color(0xff00ff)); - table.put("maroon", new Color(0x800000)); - table.put("mediumaquamarine", new Color(0x66cdaa)); - table.put("mediumblue", new Color(0x0000cd)); - table.put("mediumorchid", new Color(0xba55d3)); - table.put("mediumpurple", new Color(0x9370d8)); - table.put("mediumseagreen", new Color(0x3cb371)); - table.put("mediumslateblue", new Color(0x7b68ee)); - table.put("mediumspringgreen", new Color(0x00fa9a)); - table.put("mediumturquoise", new Color(0x48d1cc)); - table.put("mediumvioletred", new Color(0xc71585)); - table.put("midnightblue", new Color(0x191970)); - table.put("mintcream", new Color(0xf5fffa)); - table.put("mistyrose", new Color(0xffe4e1)); - table.put("moccasin", new Color(0xffe4b5)); - table.put("navajowhite", new Color(0xffdead)); - table.put("navy", new Color(0x000080)); - table.put("oldlace", new Color(0xfdf5e6)); - table.put("olive", new Color(0x808000)); - table.put("olivedrab", new Color(0x6b8e23)); - table.put("orange", new Color(0xffa500)); - table.put("orangered", new Color(0xff4500)); - table.put("orchid", new Color(0xda70d6)); - table.put("palegoldenrod", new Color(0xeee8aa)); - table.put("palegreen", new Color(0x98fb98)); - table.put("paleturquoise", new Color(0xafeeee)); - table.put("palevioletred", new Color(0xd87093)); - table.put("papayawhip", new Color(0xffefd5)); - table.put("peachpuff", new Color(0xffdab9)); - table.put("peru", new Color(0xcd853f)); - table.put("pink", new Color(0xffc0cb)); - table.put("plum", new Color(0xdda0dd)); - table.put("powderblue", new Color(0xb0e0e6)); - table.put("purple", new Color(0x800080)); - table.put("red", new Color(0xff0000)); - table.put("rosybrown", new Color(0xbc8f8f)); - table.put("royalblue", new Color(0x4169e1)); - table.put("saddlebrown", new Color(0x8b4513)); - table.put("salmon", new Color(0xfa8072)); - table.put("sandybrown", new Color(0xf4a460)); - table.put("seagreen", new Color(0x2e8b57)); - table.put("seashell", new Color(0xfff5ee)); - table.put("sienna", new Color(0xa0522d)); - table.put("silver", new Color(0xc0c0c0)); - table.put("skyblue", new Color(0x87ceeb)); - table.put("slateblue", new Color(0x6a5acd)); - table.put("slategray", new Color(0x708090)); - table.put("snow", new Color(0xfffafa)); - table.put("springgreen", new Color(0x00ff7f)); - table.put("steelblue", new Color(0x4682b4)); - table.put("tan", new Color(0xd2b48c)); - table.put("teal", new Color(0x008080)); - table.put("thistle", new Color(0xd8bfd8)); - table.put("tomato", new Color(0xff6347)); - table.put("turquoise", new Color(0x40e0d0)); - table.put("violet", new Color(0xee82ee)); - table.put("violetred", new Color(0xd02090)); - table.put("wheat", new Color(0xf5deb3)); - table.put("white", new Color(0xffffff)); - table.put("whitesmoke", new Color(0xf5f5f5)); - table.put("yellow", new Color(0xffff00)); - table.put("yellowgreen", new Color(0x9acd32)); - - colorTable = Collections.unmodifiableMap(table); - } - - static ColorTable singleton = new ColorTable(); - - /** Creates a new instance of ColorTable */ - protected ColorTable() { -// buildColorList(); - } - - static public ColorTable instance() { return singleton; } - - public Color lookupColor(String name) { - return colorTable.get(name.toLowerCase()); - } - - public static Color parseColor(String val) - { - Color retVal = null; - - if ("".equals(val)) - { - return null; - } - - if (val.charAt(0) == '#') - { - String hexStrn = val.substring(1); - - if (hexStrn.length() == 3) - { - hexStrn = "" + hexStrn.charAt(0) + hexStrn.charAt(0) + hexStrn.charAt(1) + hexStrn.charAt(1) + hexStrn.charAt(2) + hexStrn.charAt(2); - } - int hexVal = parseHex(hexStrn); - - retVal = new Color(hexVal); - } - else - { - final String number = "\\s*(((\\d+)(\\.\\d*)?)|(\\.\\d+))(%)?\\s*"; - final Matcher rgbMatch = Pattern.compile("rgb\\(" + number + "," + number + "," + number + "\\)", Pattern.CASE_INSENSITIVE).matcher(""); - - rgbMatch.reset(val); - if (rgbMatch.matches()) - { - float rr = Float.parseFloat(rgbMatch.group(1)); - float gg = Float.parseFloat(rgbMatch.group(7)); - float bb = Float.parseFloat(rgbMatch.group(13)); - rr /= "%".equals(rgbMatch.group(6)) ? 100 : 255; - gg /= "%".equals(rgbMatch.group(12)) ? 100 : 255; - bb /= "%".equals(rgbMatch.group(18)) ? 100 : 255; - retVal = new Color(rr, gg, bb); - } - else - { - Color lookupCol = ColorTable.instance().lookupColor(val); - if (lookupCol != null) retVal = lookupCol; - } - } - - return retVal; - } - - public static int parseHex(String val) - { - int retVal = 0; - - for (int i = 0; i < val.length(); i++) - { - retVal <<= 4; - - char ch = val.charAt(i); - if (ch >= '0' && ch <= '9') - { - retVal |= ch - '0'; - } - else if (ch >= 'a' && ch <= 'z') - { - retVal |= ch - 'a' + 10; - } - else if (ch >= 'A' && ch <= 'Z') - { - retVal |= ch - 'A' + 10; - } - else throw new RuntimeException(); - } - - return retVal; - } - -} --- a/src/com/kitfox/svg/xml/NumberWithUnits.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on February 18, 2004, 2:43 PM - */ - -package com.kitfox.svg.xml; - -import java.io.Serializable; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class NumberWithUnits implements Serializable -{ - public static final long serialVersionUID = 0; - - public static final int UT_UNITLESS = 0; - public static final int UT_PX = 1; //Pixels - public static final int UT_CM = 2; //Centimeters - public static final int UT_MM = 3; //Millimeters - public static final int UT_IN = 4; //Inches - public static final int UT_EM = 5; //Default font height - public static final int UT_EX = 6; //Height of character 'x' in default font - public static final int UT_PT = 7; //Points - 1/72 of an inch - public static final int UT_PC = 8; //Picas - 1/6 of an inch - public static final int UT_PERCENT = 9; //Percent - relative width - - float value = 0f; - int unitType = UT_UNITLESS; - - /** Creates a new instance of NumberWithUnits */ - public NumberWithUnits() - { - } - - public NumberWithUnits(String value) - { - set(value); - } - - public NumberWithUnits(float value, int unitType) - { - this.value = value; - this.unitType = unitType; - } - - public float getValue() { return value; } - public int getUnits() { return unitType; } - - public void set(String value) - { - this.value = XMLParseUtil.findFloat(value); - unitType = UT_UNITLESS; - - if (value.indexOf("px") != -1) { unitType = UT_PX; return; } - if (value.indexOf("cm") != -1) { unitType = UT_CM; return; } - if (value.indexOf("mm") != -1) { unitType = UT_MM; return; } - if (value.indexOf("in") != -1) { unitType = UT_IN; return; } - if (value.indexOf("em") != -1) { unitType = UT_EM; return; } - if (value.indexOf("ex") != -1) { unitType = UT_EX; return; } - if (value.indexOf("pt") != -1) { unitType = UT_PT; return; } - if (value.indexOf("pc") != -1) { unitType = UT_PC; return; } - if (value.indexOf("%") != -1) { unitType = UT_PERCENT; return; } - } - - public static String unitsAsString(int unitIdx) - { - switch (unitIdx) - { - default: - return ""; - case UT_PX: - return "px"; - case UT_CM: - return "cm"; - case UT_MM: - return "mm"; - case UT_IN: - return "in"; - case UT_EM: - return "em"; - case UT_EX: - return "ex"; - case UT_PT: - return "pt"; - case UT_PC: - return "pc"; - case UT_PERCENT: - return "%"; - } - } - - @Override - public String toString() - { - return "" + value + unitsAsString(unitType); - } - - @Override - public boolean equals(Object obj) - { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final NumberWithUnits other = (NumberWithUnits) obj; - if (Float.floatToIntBits(this.value) != Float.floatToIntBits(other.value)) { - return false; - } - if (this.unitType != other.unitType) { - return false; - } - return true; - } - - @Override - public int hashCode() - { - int hash = 5; - hash = 37 * hash + Float.floatToIntBits(this.value); - hash = 37 * hash + this.unitType; - return hash; - } - - -} --- a/src/com/kitfox/svg/xml/ReadableXMLElement.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on September 1, 2003, 1:46 AM - */ - -package com.kitfox.svg.xml; - -import org.w3c.dom.*; -import java.net.*; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public interface ReadableXMLElement { - - /** - * Initializes this element from the passed DOM tree. - * @param root - DOM tree to build from - * @param docRoot - URL of the document this DOM tree was created from - */ - public void read(Element root, URL docRoot); - -} --- a/src/com/kitfox/svg/xml/StyleAttribute.java +++ /dev/null @@ -1,326 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on January 27, 2004, 2:53 PM - */ - -package com.kitfox.svg.xml; - -import com.kitfox.svg.SVGConst; -import java.awt.*; -import java.io.*; -import java.net.*; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.regex.*; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class StyleAttribute implements Serializable -{ - public static final long serialVersionUID = 0; - - static final Pattern patternUrl = Pattern.compile("\\s*url\\((.*)\\)\\s*"); - static final Pattern patternFpNumUnits = Pattern.compile("\\s*([-+]?((\\d*\\.\\d+)|(\\d+))([-+]?[eE]\\d+)?)\\s*(px|cm|mm|in|pc|pt|em|ex)\\s*"); - String name; - String stringValue; - - boolean colorCompatable = false; - boolean urlCompatable = false; - - /** Creates a new instance of StyleAttribute */ - public StyleAttribute() - { - this(null, null); - } - - public StyleAttribute(String name) - { - this.name = name; - stringValue = null; - } - - public StyleAttribute(String name, String stringValue) - { - this.name = name; - this.stringValue = stringValue; - } - - public String getName() { - return name; - } - - public StyleAttribute setName(String name) - { - this.name = name; - return this; - } - - public String getStringValue() - { - return stringValue; - } - - public String[] getStringList() - { - return XMLParseUtil.parseStringList(stringValue); - } - - public void setStringValue(String value) - { - stringValue = value; - } - - public boolean getBooleanValue() { - return stringValue.toLowerCase().equals("true"); - } - - public int getIntValue() { - return XMLParseUtil.findInt(stringValue); - } - - public int[] getIntList() { - return XMLParseUtil.parseIntList(stringValue); - } - - public double getDoubleValue() { - return XMLParseUtil.findDouble(stringValue); - } - - public double[] getDoubleList() { - return XMLParseUtil.parseDoubleList(stringValue); - } - - public float getFloatValue() { - return XMLParseUtil.findFloat(stringValue); - } - - public float[] getFloatList() { - return XMLParseUtil.parseFloatList(stringValue); - } - - public float getRatioValue() { - return (float)XMLParseUtil.parseRatio(stringValue); -// try { return Float.parseFloat(stringValue); } -// catch (Exception e) {} -// return 0f; - } - - public String getUnits() { - Matcher m = patternFpNumUnits.matcher(stringValue); - if (!m.matches()) return null; - return m.group(6); - } - - public NumberWithUnits getNumberWithUnits() { - return XMLParseUtil.parseNumberWithUnits(stringValue); - } - - public float getFloatValueWithUnits() - { - NumberWithUnits number = getNumberWithUnits(); - return convertUnitsToPixels(number.getUnits(), number.getValue()); - } - - public float[] getFloatListWithUnits() - { - String[] values = getStringList(); - float[] result = new float[values.length]; - for (int i = 0; i < result.length; i++) - { - NumberWithUnits number = XMLParseUtil.parseNumberWithUnits(stringValue); - result[i] = convertUnitsToPixels(number.getUnits(), number.getValue()); - } - return result; - } - - static public float convertUnitsToPixels(int unitType, float value) - { - if (unitType == NumberWithUnits.UT_UNITLESS || unitType == NumberWithUnits.UT_PERCENT) - { - return value; - } - - float pixPerInch; - try - { - pixPerInch = (float)Toolkit.getDefaultToolkit().getScreenResolution(); - } - catch (HeadlessException ex) - { - //default to 72 dpi - pixPerInch = 72; - } - final float inchesPerCm = .3936f; - - switch (unitType) - { - case NumberWithUnits.UT_IN: - return value * pixPerInch; - case NumberWithUnits.UT_CM: - return value * inchesPerCm * pixPerInch; - case NumberWithUnits.UT_MM: - return value * .1f * inchesPerCm * pixPerInch; - case NumberWithUnits.UT_PT: - return value * (1f / 72f) * pixPerInch; - case NumberWithUnits.UT_PC: - return value * (1f / 6f) * pixPerInch; - } - - return value; - } - - public Color getColorValue() - { - return ColorTable.parseColor(stringValue); - } - - public String parseURLFn() - { - Matcher matchUrl = patternUrl.matcher(stringValue); - if (!matchUrl.matches()) - { - return null; - } - return matchUrl.group(1); - } - - public URL getURLValue(URL docRoot) - { - String fragment = parseURLFn(); - if (fragment == null) return null; - try { - return new URL(docRoot, fragment); - } - catch (Exception e) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, null, e); - return null; - } - } - - public URL getURLValue(URI docRoot) - { - String fragment = parseURLFn(); - if (fragment == null) return null; - try { - URI ref = docRoot.resolve(fragment); - return ref.toURL(); - } - catch (Exception e) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, null, e); - return null; - } - } - - public URI getURIValue() - { - return getURIValue(null); - } - - /** - * Parse this sytle attribute as a URL and return it in URI form resolved - * against the passed base. - * - * @param base - URI to resolve against. If null, will return value without - * attempting to resolve it. - */ - public URI getURIValue(URI base) - { - try { - String fragment = parseURLFn(); - if (fragment == null) fragment = stringValue.replaceAll("\\s+", ""); - if (fragment == null) return null; - - //====================== - //This gets around a bug in the 1.5.0 JDK - if (Pattern.matches("[a-zA-Z]:!\\\\.*", fragment)) - { - File file = new File(fragment); - return file.toURI(); - } - //====================== - - //[scheme:]scheme-specific-part[#fragment] - - URI uriFrag = new URI(fragment); - if (uriFrag.isAbsolute()) - { - //Has scheme - return uriFrag; - } - - if (base == null) return uriFrag; - - URI relBase = new URI(null, base.getSchemeSpecificPart(), null); - URI relUri; - if (relBase.isOpaque()) - { - relUri = new URI(null, base.getSchemeSpecificPart(), uriFrag.getFragment()); - } - else - { - relUri = relBase.resolve(uriFrag); - } - return new URI(base.getScheme() + ":" + relUri); - } - catch (Exception e) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, null, e); - return null; - } - } - - public static void main(String[] args) - { - try - { - URI uri = new URI("jar:http://www.kitfox.com/jackal/jackal.jar!/res/doc/about.svg"); - uri = uri.resolve("#myFragment"); - - System.err.println(uri.toString()); - - uri = new URI("http://www.kitfox.com/jackal/jackal.html"); - uri = uri.resolve("#myFragment"); - - System.err.println(uri.toString()); - } - catch (Exception e) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, null, e); - } - } -} --- a/src/com/kitfox/svg/xml/StyleSheet.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package com.kitfox.svg.xml; - -import com.kitfox.svg.SVGConst; -import java.util.HashMap; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * - * @author kitfox - */ -public class StyleSheet -{ - HashMap ruleMap = new HashMap(); - - public static StyleSheet parseSheet(String src) - { - //Implement CS parser later - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, - "CSS parser not implemented yet"); - return new StyleSheet(); - } - - public void addStyleRule(StyleSheetRule rule, String value) - { - ruleMap.put(rule, value); - } - - public boolean getStyle(StyleAttribute attrib, String tagName, String cssClass) - { - StyleSheetRule rule = new StyleSheetRule(attrib.getName(), tagName, cssClass); - String value = (String)ruleMap.get(rule); - - if (value != null) - { - attrib.setStringValue(value); - return true; - } - - //Try again using just class name - rule = new StyleSheetRule(attrib.getName(), null, cssClass); - value = (String)ruleMap.get(rule); - - if (value != null) - { - attrib.setStringValue(value); - return true; - } - - //Try again using just tag name - rule = new StyleSheetRule(attrib.getName(), tagName, null); - value = (String)ruleMap.get(rule); - - if (value != null) - { - attrib.setStringValue(value); - return true; - } - - return false; - } - -} --- a/src/com/kitfox/svg/xml/StyleSheetRule.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package com.kitfox.svg.xml; - -/** - * - * @author kitfox - */ -public class StyleSheetRule -{ - final String styleName; - final String tag; - final String className; - - public StyleSheetRule(String styleName, String tag, String className) - { - this.styleName = styleName; - this.tag = tag; - this.className = className; - } - - @Override - public int hashCode() - { - int hash = 7; - hash = 13 * hash + (this.styleName != null ? this.styleName.hashCode() : 0); - hash = 13 * hash + (this.tag != null ? this.tag.hashCode() : 0); - hash = 13 * hash + (this.className != null ? this.className.hashCode() : 0); - return hash; - } - - @Override - public boolean equals(Object obj) - { - if (obj == null) - { - return false; - } - if (getClass() != obj.getClass()) - { - return false; - } - final StyleSheetRule other = (StyleSheetRule) obj; - if ((this.styleName == null) ? (other.styleName != null) : !this.styleName.equals(other.styleName)) - { - return false; - } - if ((this.tag == null) ? (other.tag != null) : !this.tag.equals(other.tag)) - { - return false; - } - if ((this.className == null) ? (other.className != null) : !this.className.equals(other.className)) - { - return false; - } - return true; - } - -} --- a/src/com/kitfox/svg/xml/WritableXMLElement.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on September 1, 2003, 1:46 AM - */ - -package com.kitfox.svg.xml; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public interface WritableXMLElement { - - /** - * Initializes this element from the passed DOM tree. - * @param root - DOM tree to build from - * @param docRoot - URL of the document this DOM tree was created from - */ -// public void write(Element root, URL docRoot); - -} --- a/src/com/kitfox/svg/xml/XMLParseUtil.java +++ /dev/null @@ -1,828 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on February 18, 2004, 1:49 PM - */ - -package com.kitfox.svg.xml; - -import com.kitfox.svg.SVGConst; -import org.w3c.dom.*; -import java.awt.*; -import java.net.*; -import java.util.*; -import java.util.regex.*; -import java.lang.reflect.*; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class XMLParseUtil -{ - static final Pattern fpPat = Pattern.compile("([-+]?((\\d*\\.\\d+)|(\\d+))([eE][+-]?\\d+)?)(\\%|in|cm|mm|pt|pc|px|em|ex)?"); - static final Pattern intPat = Pattern.compile("[-+]?\\d+"); - static final Pattern quotePat = Pattern.compile("^'|'$"); - - - /** Creates a new instance of XMLParseUtil */ - private XMLParseUtil() - { - } - - /** - * Scans the tag's children and returns the first text element found - */ - public static String getTagText(Element ele) - { - NodeList nl = ele.getChildNodes(); - int size = nl.getLength(); - - Node node = null; - int i = 0; - for (; i < size; i++) - { - node = nl.item(i); - if (node instanceof Text) break; - } - if (i == size || node == null) return null; - - return ((Text)node).getData(); - } - - /** - * Returns the first node that is a direct child of root with the corresponding - * name. Does not search children of children. - */ - public static Element getFirstChild(Element root, String name) - { - NodeList nl = root.getChildNodes(); - int size = nl.getLength(); - for (int i = 0; i < size; i++) - { - Node node = nl.item(i); - if (!(node instanceof Element)) continue; - Element ele = (Element)node; - if (ele.getTagName().equals(name)) return ele; - } - - return null; - } - - public static String[] parseStringList(String list) - { -// final Pattern patWs = Pattern.compile("\\s+"); - final Matcher matchWs = Pattern.compile("[^\\s]+").matcher(""); - matchWs.reset(list); - - LinkedList matchList = new LinkedList(); - while (matchWs.find()) - { - matchList.add(matchWs.group()); - } - - String[] retArr = new String[matchList.size()]; - return (String[])matchList.toArray(retArr); - } - - public static boolean isDouble(String val) - { - Matcher m = fpPat.matcher(val); - return m.matches(); - } - - public static double parseDouble(String val) - { - /* - if (val == null) return 0.0; - - double retVal = 0.0; - try - { retVal = Double.parseDouble(val); } - catch (Exception e) - {} - return retVal; - */ - return findDouble(val); - } - - /** - * Searches the given string for the first floating point number it contains, - * parses and returns it. - */ - public synchronized static double findDouble(String val) - { - if (val == null) return 0; - - Matcher matcher = fpPat.matcher(val); - try - { - if (!matcher.find()) return 0; - } - catch (StringIndexOutOfBoundsException e) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, - "XMLParseUtil: regex parse problem: '" + val + "'", e); - } - - val = matcher.group(1); - //System.err.println("Parsing " + val); - - double retVal = 0; - try - { - retVal = Double.parseDouble(val); - - float pixPerInch; - try { - pixPerInch = (float)Toolkit.getDefaultToolkit().getScreenResolution(); - } - catch (NoClassDefFoundError err) - { - //Default value for headless X servers - pixPerInch = 72; - } - final float inchesPerCm = .3936f; - final String units = matcher.group(6); - - if ("%".equals(units)) retVal /= 100; - else if ("in".equals(units)) - { - retVal *= pixPerInch; - } - else if ("cm".equals(units)) - { - retVal *= inchesPerCm * pixPerInch; - } - else if ("mm".equals(units)) - { - retVal *= inchesPerCm * pixPerInch * .1f; - } - else if ("pt".equals(units)) - { - retVal *= (1f / 72f) * pixPerInch; - } - else if ("pc".equals(units)) - { - retVal *= (1f / 6f) * pixPerInch; - } - } - catch (Exception e) - {} - return retVal; - } - - /** - * Scans an input string for double values. For each value found, places - * in a list. This method regards any characters not part of a floating - * point value to be seperators. Thus this will parse whitespace seperated, - * comma seperated, and many other separation schemes correctly. - */ - public synchronized static double[] parseDoubleList(String list) - { - if (list == null) return null; - Matcher matcher = fpPat.matcher(list); - - LinkedList doubList = new LinkedList(); - while (matcher.find()) - { - String val = matcher.group(1); - doubList.add(Double.valueOf(val)); - } - - double[] retArr = new double[doubList.size()]; - Iterator it = doubList.iterator(); - int idx = 0; - while (it.hasNext()) - { - retArr[idx++] = ((Double)it.next()).doubleValue(); - } - - return retArr; - } - - public static float parseFloat(String val) - { - /* - if (val == null) return 0f; - - float retVal = 0f; - try - { retVal = Float.parseFloat(val); } - catch (Exception e) - {} - return retVal; - */ - return findFloat(val); - } - - /** - * Searches the given string for the first floating point number it contains, - * parses and returns it. - */ - public synchronized static float findFloat(String val) - { - if (val == null) return 0f; - Matcher matcher = fpPat.matcher(val); - if (!matcher.find()) return 0f; - - val = matcher.group(1); - //System.err.println("Parsing " + val); - - float retVal = 0f; - try - { - retVal = Float.parseFloat(val); - String units = matcher.group(6); - if ("%".equals(units)) retVal /= 100; - } - catch (Exception e) - {} - return retVal; - } - - public synchronized static float[] parseFloatList(String list) - { - if (list == null) return null; - Matcher matcher = fpPat.matcher(list); - - LinkedList floatList = new LinkedList(); - while (matcher.find()) - { - String val = matcher.group(1); - floatList.add(Float.valueOf(val)); - } - - float[] retArr = new float[floatList.size()]; - Iterator it = floatList.iterator(); - int idx = 0; - while (it.hasNext()) - { - retArr[idx++] = ((Float)it.next()).floatValue(); - } - - return retArr; - } - - public static int parseInt(String val) - { - if (val == null) return 0; - - int retVal = 0; - try - { retVal = Integer.parseInt(val); } - catch (Exception e) - {} - return retVal; - } - - /** - * Searches the given string for the first integer point number it contains, - * parses and returns it. - */ - public static int findInt(String val) - { - if (val == null) return 0; - Matcher matcher = intPat.matcher(val); - if (!matcher.find()) return 0; - - val = matcher.group(); - //System.err.println("Parsing " + val); - - int retVal = 0; - try - { retVal = Integer.parseInt(val); } - catch (Exception e) - {} - return retVal; - } - - public static int[] parseIntList(String list) - { - if (list == null) return null; - Matcher matcher = intPat.matcher(list); - - LinkedList intList = new LinkedList(); - while (matcher.find()) - { - String val = matcher.group(); - intList.add(Integer.valueOf(val)); - } - - int[] retArr = new int[intList.size()]; - Iterator it = intList.iterator(); - int idx = 0; - while (it.hasNext()) - { - retArr[idx++] = ((Integer)it.next()).intValue(); - } - - return retArr; - } -/* - public static int parseHex(String val) - { - int retVal = 0; - - for (int i = 0; i < val.length(); i++) - { - retVal <<= 4; - - char ch = val.charAt(i); - if (ch >= '0' && ch <= '9') - { - retVal |= ch - '0'; - } - else if (ch >= 'a' && ch <= 'z') - { - retVal |= ch - 'a' + 10; - } - else if (ch >= 'A' && ch <= 'Z') - { - retVal |= ch - 'A' + 10; - } - else throw new RuntimeException(); - } - - return retVal; - } -*/ - /** - * The input string represents a ratio. Can either be specified as a - * double number on the range of [0.0 1.0] or as a percentage [0% 100%] - */ - public static double parseRatio(String val) - { - if (val == null || val.equals("")) return 0.0; - - if (val.charAt(val.length() - 1) == '%') - { - parseDouble(val.substring(0, val.length() - 1)); - } - return parseDouble(val); - } - - public static NumberWithUnits parseNumberWithUnits(String val) - { - if (val == null) return null; - - return new NumberWithUnits(val); - } -/* - public static Color parseColor(String val) - { - Color retVal = null; - - if (val.charAt(0) == '#') - { - String hexStrn = val.substring(1); - - if (hexStrn.length() == 3) - { - hexStrn = "" + hexStrn.charAt(0) + hexStrn.charAt(0) + hexStrn.charAt(1) + hexStrn.charAt(1) + hexStrn.charAt(2) + hexStrn.charAt(2); - } - int hexVal = parseHex(hexStrn); - - retVal = new Color(hexVal); - } - else - { - final Matcher rgbMatch = Pattern.compile("rgb\\((\\d+),(\\d+),(\\d+)\\)", Pattern.CASE_INSENSITIVE).matcher(""); - - rgbMatch.reset(val); - if (rgbMatch.matches()) - { - int r = Integer.parseInt(rgbMatch.group(1)); - int g = Integer.parseInt(rgbMatch.group(2)); - int b = Integer.parseInt(rgbMatch.group(3)); - retVal = new Color(r, g, b); - } - else - { - Color lookupCol = ColorTable.instance().lookupColor(val); - if (lookupCol != null) retVal = lookupCol; - } - } - - return retVal; - } -*/ - /** - * Parses the given attribute of this tag and returns it as a String. - */ - public static String getAttribString(Element ele, String name) - { - return ele.getAttribute(name); - } - - /** - * Parses the given attribute of this tag and returns it as an int. - */ - public static int getAttribInt(Element ele, String name) - { - String sval = ele.getAttribute(name); - int val = 0; - try { val = Integer.parseInt(sval); } catch (Exception e) {} - - return val; - } - - /** - * Parses the given attribute of this tag as a hexadecimal encoded string and - * returns it as an int - */ - public static int getAttribIntHex(Element ele, String name) - { - String sval = ele.getAttribute(name); - int val = 0; - try { val = Integer.parseInt(sval, 16); } catch (Exception e) {} - - return val; - } - - /** - * Parses the given attribute of this tag and returns it as a float - */ - public static float getAttribFloat(Element ele, String name) - { - String sval = ele.getAttribute(name); - float val = 0.0f; - try { val = Float.parseFloat(sval); } catch (Exception e) {} - - return val; - } - - /** - * Parses the given attribute of this tag and returns it as a double. - */ - public static double getAttribDouble(Element ele, String name) - { - String sval = ele.getAttribute(name); - double val = 0.0; - try { val = Double.parseDouble(sval); } catch (Exception e) {} - - return val; - } - - /** - * Parses the given attribute of this tag and returns it as a boolean. - * Essentially compares the lower case textual value to the string "true" - */ - public static boolean getAttribBoolean(Element ele, String name) - { - String sval = ele.getAttribute(name); - - return sval.toLowerCase().equals("true"); - } - - public static URL getAttribURL(Element ele, String name, URL docRoot) - { - String sval = ele.getAttribute(name); - - try - { - return new URL(docRoot, sval); - } - catch (Exception e) - { - return null; - } - } - - /** - * Returns the first ReadableXMLElement with the given name - */ - public static ReadableXMLElement getElement(Class classType, Element root, String name, URL docRoot) - { - if (root == null) return null; - - //Do not process if not a LoadableObject - if (!ReadableXMLElement.class.isAssignableFrom(classType)) - { - return null; - } - - NodeList nl = root.getChildNodes(); - int size = nl.getLength(); - for (int i = 0; i < size; i++) - { - Node node = nl.item(i); - if (!(node instanceof Element)) continue; - Element ele = (Element)node; - if (!ele.getTagName().equals(name)) continue; - - ReadableXMLElement newObj = null; - try - { - newObj = (ReadableXMLElement)classType.newInstance(); - } - catch (Exception e) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, null, e); - continue; - } - newObj.read(ele, docRoot); - - if (newObj == null) continue; - - return newObj; - } - - return null; - } - - /** - * Returns a HashMap of nodes that are children of root. All nodes will - * be of class classType and have a tag name of 'name'. 'key' is - * an attribute of tag 'name' who's string value will be used as the key - * in the HashMap - */ - public static HashMap getElementHashMap(Class classType, Element root, String name, String key, URL docRoot) - { - if (root == null) return null; - - //Do not process if not a LoadableObject - if (!ReadableXMLElement.class.isAssignableFrom(classType)) - { - return null; - } - - HashMap retMap = new HashMap(); - - NodeList nl = root.getChildNodes(); - int size = nl.getLength(); - for (int i = 0; i < size; i++) - { - Node node = nl.item(i); - if (!(node instanceof Element)) continue; - Element ele = (Element)node; - if (!ele.getTagName().equals(name)) continue; - - ReadableXMLElement newObj = null; - try - { - newObj = (ReadableXMLElement)classType.newInstance(); - } - catch (Exception e) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, null, e); - continue; - } - newObj.read(ele, docRoot); - - if (newObj == null) continue; - - String keyVal = getAttribString(ele, key); - retMap.put(keyVal, newObj); - } - - return retMap; - } - - public static HashSet getElementHashSet(Class classType, Element root, String name, URL docRoot) - { - if (root == null) return null; - - //Do not process if not a LoadableObject - if (!ReadableXMLElement.class.isAssignableFrom(classType)) - { - return null; - } - - HashSet retSet = new HashSet(); - - NodeList nl = root.getChildNodes(); - int size = nl.getLength(); - for (int i = 0; i < size; i++) - { - Node node = nl.item(i); - if (!(node instanceof Element)) continue; - Element ele = (Element)node; - if (!ele.getTagName().equals(name)) continue; - - ReadableXMLElement newObj = null; - try - { - newObj = (ReadableXMLElement)classType.newInstance(); - } - catch (Exception e) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, null, e); - continue; - } - newObj.read(ele, docRoot); - - if (newObj == null) - { - continue; - } - - retSet.add(newObj); - } - - return retSet; - } - - - public static LinkedList getElementLinkedList(Class classType, Element root, String name, URL docRoot) - { - if (root == null) return null; - - //Do not process if not a LoadableObject - if (!ReadableXMLElement.class.isAssignableFrom(classType)) - { - return null; - } - - NodeList nl = root.getChildNodes(); - LinkedList elementCache = new LinkedList(); - int size = nl.getLength(); - for (int i = 0; i < size; i++) - { - Node node = nl.item(i); - if (!(node instanceof Element)) continue; - Element ele = (Element)node; - if (!ele.getTagName().equals(name)) continue; - - ReadableXMLElement newObj = null; - try - { - newObj = (ReadableXMLElement)classType.newInstance(); - } - catch (Exception e) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, null, e); - continue; - } - newObj.read(ele, docRoot); - - elementCache.addLast(newObj); - } - - return elementCache; - } - - public static Object[] getElementArray(Class classType, Element root, String name, URL docRoot) - { - if (root == null) return null; - - //Do not process if not a LoadableObject - if (!ReadableXMLElement.class.isAssignableFrom(classType)) - { - return null; - } - - LinkedList elementCache = getElementLinkedList(classType, root, name, docRoot); - - Object[] retArr = (Object[])Array.newInstance(classType, elementCache.size()); - return elementCache.toArray(retArr); - } - - /** - * Takes a number of tags of name 'name' that are children of 'root', and - * looks for attributes of 'attrib' on them. Converts attributes to an - * int and returns in an array. - */ - public static int[] getElementArrayInt(Element root, String name, String attrib) - { - if (root == null) return null; - - NodeList nl = root.getChildNodes(); - LinkedList elementCache = new LinkedList(); - int size = nl.getLength(); - - for (int i = 0; i < size; i++) - { - Node node = nl.item(i); - if (!(node instanceof Element)) continue; - Element ele = (Element)node; - if (!ele.getTagName().equals(name)) continue; - - String valS = ele.getAttribute(attrib); - int eleVal = 0; - try { eleVal = Integer.parseInt(valS); } - catch (Exception e) {} - - elementCache.addLast(new Integer(eleVal)); - } - - int[] retArr = new int[elementCache.size()]; - Iterator it = elementCache.iterator(); - int idx = 0; - while (it.hasNext()) - { - retArr[idx++] = it.next().intValue(); - } - - return retArr; - } - - /** - * Takes a number of tags of name 'name' that are children of 'root', and - * looks for attributes of 'attrib' on them. Converts attributes to an - * int and returns in an array. - */ - public static String[] getElementArrayString(Element root, String name, String attrib) - { - if (root == null) return null; - - NodeList nl = root.getChildNodes(); - LinkedList elementCache = new LinkedList(); - int size = nl.getLength(); - - for (int i = 0; i < size; i++) - { - Node node = nl.item(i); - if (!(node instanceof Element)) continue; - Element ele = (Element)node; - if (!ele.getTagName().equals(name)) continue; - - String valS = ele.getAttribute(attrib); - - elementCache.addLast(valS); - } - - String[] retArr = new String[elementCache.size()]; - Iterator it = elementCache.iterator(); - int idx = 0; - while (it.hasNext()) - { - retArr[idx++] = it.next(); - } - - return retArr; - } - - /** - * Takes a CSS style string and retursn a hash of them. - * @param styleString - A CSS formatted string of styles. Eg, - * "font-size:12;fill:#d32c27;fill-rule:evenodd;stroke-width:1pt;" - */ - public static HashMap parseStyle(String styleString) { - return parseStyle(styleString, new HashMap()); - } - - /** - * Takes a CSS style string and returns a hash of them. - * @param styleString - A CSS formatted string of styles. Eg, - * "font-size:12;fill:#d32c27;fill-rule:evenodd;stroke-width:1pt;" - * @param map - A map to which these styles will be added - */ - public static HashMap parseStyle(String styleString, HashMap map) { - final Pattern patSemi = Pattern.compile(";"); - - String[] styles = patSemi.split(styleString); - - for (int i = 0; i < styles.length; i++) - { - if (styles[i].length() == 0) - { - continue; - } - - int colon = styles[i].indexOf(':'); - if (colon == -1) - { - continue; - } - String key = styles[i].substring(0, colon).trim().intern(); - String value = quotePat.matcher(styles[i].substring(colon + 1).trim()).replaceAll("").intern(); - - map.put(key, new StyleAttribute(key, value)); - } - - return map; - } -} --- a/src/com/kitfox/svg/xml/cpx/CPXConsts.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on February 12, 2004, 12:51 PM - */ - -package com.kitfox.svg.xml.cpx; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public interface CPXConsts { - - static final byte[] MAGIC_NUMBER = {'C', 'P', 'X', 0}; - - static final int XL_PLAIN = 0; - static final int XL_ZIP_CRYPT = 1; -} --- a/src/com/kitfox/svg/xml/cpx/CPXInputStream.java +++ /dev/null @@ -1,317 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on February 12, 2004, 10:34 AM - */ - -package com.kitfox.svg.xml.cpx; - -import com.kitfox.svg.SVGConst; -import java.io.*; -import java.util.zip.*; -import java.security.*; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * This class reads/decodes the CPX file format. This format is a simple - * compression/encryption transformer for XML data. This stream takes in - * encrypted XML and outputs decrypted. It does this by checking for a magic - * number at the start of the stream. If absent, it treats the stream as - * raw XML data and passes it through unaltered. This is to aid development - * in debugging versions, where the XML files will not be in CPX format. - * - * See http://java.sun.com/developer/technicalArticles/Security/Crypto/ - * - * @author Mark McKay - * @author Mark McKay - */ -public class CPXInputStream extends FilterInputStream implements CPXConsts { - - - SecureRandom sec = new SecureRandom(); - - Inflater inflater = new Inflater(); - - int xlateMode; - - //Keep header bytes in case this stream turns out to be plain text - byte[] head = new byte[4]; - int headSize = 0; - int headPtr = 0; - - boolean reachedEOF = false; - byte[] inBuffer = new byte[2048]; - byte[] decryptBuffer = new byte[2048]; - - /** - * Creates a new instance of CPXInputStream - * @param in - * @throws java.io.IOException - */ - public CPXInputStream(InputStream in) throws IOException { - super(in); - - //Determine processing type - for (int i = 0; i < 4; i++) - { - int val = in.read(); - head[i] = (byte)val; - if (val == -1 || head[i] != MAGIC_NUMBER[i]) - { - headSize = i + 1; - xlateMode = XL_PLAIN; - return; - } - } - - xlateMode = XL_ZIP_CRYPT; - } - - /** - * We do not allow marking - */ - @Override - public boolean markSupported() { return false; } - - /** - * Closes this input stream and releases any system resources - * associated with the stream. - * This - * method simply performs in.close(). - * - * @exception IOException if an I/O error occurs. - * @see java.io.FilterInputStream#in - */ - @Override - public void close() throws IOException { - reachedEOF = true; - in.close(); - } - - /** - * Reads the next byte of data from this input stream. The value - * byte is returned as an int in the range - * 0 to 255. If no byte is available - * because the end of the stream has been reached, the value - * -1 is returned. This method blocks until input data - * is available, the end of the stream is detected, or an exception - * is thrown. - *

- * This method - * simply performs in.read() and returns the result. - * - * @return the next byte of data, or -1 if the end of the - * stream is reached. - * @exception IOException if an I/O error occurs. - * @see java.io.FilterInputStream#in - */ - @Override - public int read() throws IOException - { - final byte[] b = new byte[1]; - int retVal = read(b, 0, 1); - if (retVal == -1) return -1; - return b[0]; - } - - /** - * Reads up to byte.length bytes of data from this - * input stream into an array of bytes. This method blocks until some - * input is available. - *

- * This method simply performs the call - * read(b, 0, b.length) and returns - * the result. It is important that it does - * not do in.read(b) instead; - * certain subclasses of FilterInputStream - * depend on the implementation strategy actually - * used. - * - * @param b the buffer into which the data is read. - * @return the total number of bytes read into the buffer, or - * -1 if there is no more data because the end of - * the stream has been reached. - * @exception IOException if an I/O error occurs. - * @see java.io.FilterInputStream#read(byte[], int, int) - */ - @Override - public int read(byte[] b) throws IOException - { - return read(b, 0, b.length); - } - - /** - * Reads up to len bytes of data from this input stream - * into an array of bytes. This method blocks until some input is - * available. - *

- * This method simply performs in.read(b, off, len) - * and returns the result. - * - * @param b the buffer into which the data is read. - * @param off the start offset of the data. - * @param len the maximum number of bytes read. - * @return the total number of bytes read into the buffer, or - * -1 if there is no more data because the end of - * the stream has been reached. - * @exception IOException if an I/O error occurs. - * @see java.io.FilterInputStream#in - */ - @Override - public int read(byte[] b, int off, int len) throws IOException - { - if (reachedEOF) return -1; - - if (xlateMode == XL_PLAIN) - { - int count = 0; - //Write header if appropriate - while (headPtr < headSize && len > 0) - { - b[off++] = head[headPtr++]; - count++; - len--; - } - - return (len == 0) ? count : count + in.read(b, off, len); - } - - //Decrypt and inflate - if (inflater.needsInput() && !decryptChunk()) - { - reachedEOF = true; - - //Read remaining bytes - int numRead; - try { - numRead = inflater.inflate(b, off, len); - } - catch (Exception e) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, null, e); - return -1; - } - - if (!inflater.finished()) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, - "Inflation imncomplete"); - } - - return numRead == 0 ? -1 : numRead; - } - - try - { - return inflater.inflate(b, off, len); - } - catch (DataFormatException e) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, null, e); - return -1; - } - } - - - /** - * Call when inflater indicates that it needs more bytes. - * @return - true if we decrypted more bytes to deflate, false if we - * encountered the end of stream - * @throws java.io.IOException - */ - protected boolean decryptChunk() throws IOException - { - while (inflater.needsInput()) - { - int numInBytes = in.read(inBuffer); - if (numInBytes == -1) return false; -// int numDecryptBytes = cipher.update(inBuffer, 0, numInBytes, decryptBuffer); -// inflater.setInput(decryptBuffer, 0, numDecryptBytes); -inflater.setInput(inBuffer, 0, numInBytes); - } - - return true; - } - - /** - * This method returns 1 if we've not reached EOF, 0 if we have. Programs - * should not rely on this to determine the number of bytes that can be - * read without blocking. - */ - @Override - public int available() { return reachedEOF ? 0 : 1; } - - /** - * Skips bytes by reading them into a cached buffer - */ - @Override - public long skip(long n) throws IOException - { - int skipSize = (int)n; - if (skipSize > inBuffer.length) skipSize = inBuffer.length; - return read(inBuffer, 0, skipSize); - } - -} - -/* - import java.security.KeyPairGenerator; - import java.security.KeyPair; - import java.security.KeyPairGenerator; - import java.security.PrivateKey; - import java.security.PublicKey; - import java.security.SecureRandom; - import java.security.Cipher; - - .... - - java.security.Security.addProvider(new cryptix.provider.Cryptix()); - - SecureRandom random = new SecureRandom(SecureRandom.getSeed(30)); - KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA"); - keygen.initialize(1024, random); - keypair = keygen.generateKeyPair(); - - PublicKey pubkey = keypair.getPublic(); - PrivateKey privkey = keypair.getPrivate(); - */ - -/* - * - *Generate key pairs -KeyPairGenerator keyGen = - KeyPairGenerator.getInstance("DSA"); -KeyGen.initialize(1024, new SecureRandom(userSeed)); -KeyPair pair = KeyGen.generateKeyPair(); - */ \ No newline at end of file --- a/src/com/kitfox/svg/xml/cpx/CPXOutputStream.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on February 12, 2004, 12:50 PM - */ - -package com.kitfox.svg.xml.cpx; - -import java.io.*; -import java.util.zip.*; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class CPXOutputStream extends FilterOutputStream implements CPXConsts { - - Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION); - - /** - * Creates a new instance of CPXOutputStream - * @param os - * @throws java.io.IOException - */ - public CPXOutputStream(OutputStream os) throws IOException { - super(os); - - //Write magic number - os.write(MAGIC_NUMBER); - } - - /** - * Writes the specified byte to this output stream. - *

- * The write method of FilterOutputStream - * calls the write method of its underlying output stream, - * that is, it performs out.write(b). - *

- * Implements the abstract write method of OutputStream. - * - * @param b the byte. - * @exception IOException if an I/O error occurs. - */ - @Override - public void write(int b) throws IOException { - final byte[] buf = new byte[1]; - buf[0] = (byte)b; - write(buf, 0, 1); - } - - /** - * Writes b.length bytes to this output stream. - *

- * The write method of FilterOutputStream - * calls its write method of three arguments with the - * arguments b, 0, and - * b.length. - *

- * Note that this method does not call the one-argument - * write method of its underlying stream with the single - * argument b. - * - * @param b the data to be written. - * @exception IOException if an I/O error occurs. - * @see java.io.FilterOutputStream#write(byte[], int, int) - */ - @Override - public void write(byte b[]) throws IOException { - write(b, 0, b.length); - } - - byte[] deflateBuffer = new byte[2048]; - - /** - * Writes len bytes from the specified - * byte array starting at offset off to - * this output stream. - *

- * The write method of FilterOutputStream - * calls the write method of one argument on each - * byte to output. - *

- * Note that this method does not call the write method - * of its underlying input stream with the same arguments. Subclasses - * of FilterOutputStream should provide a more efficient - * implementation of this method. - * - * @param b the data. - * @param off the start offset in the data. - * @param len the number of bytes to write. - * @exception IOException if an I/O error occurs. - * @see java.io.FilterOutputStream#write(int) - */ - @Override - public void write(byte b[], int off, int len) throws IOException - { - deflater.setInput(b, off, len); - - processAllData(); - /* - int numDeflatedBytes; - while ((numDeflatedBytes = deflater.deflate(deflateBuffer)) != 0) - { -// byte[] cipherBuf = cipher.update(deflateBuffer, 0, numDeflatedBytes); -// out.write(cipherBytes); -out.write(deflateBuffer, 0, numDeflatedBytes); - } - */ - } - - protected void processAllData() throws IOException - { - int numDeflatedBytes; - while ((numDeflatedBytes = deflater.deflate(deflateBuffer)) != 0) - { -// byte[] cipherBuf = cipher.update(deflateBuffer, 0, numDeflatedBytes); -// out.write(cipherBytes); -out.write(deflateBuffer, 0, numDeflatedBytes); - } - } - - /** - * Flushes this output stream and forces any buffered output bytes - * to be written out to the stream. - *

- * The flush method of FilterOutputStream - * calls the flush method of its underlying output stream. - * - * @exception IOException if an I/O error occurs. - * @see java.io.FilterOutputStream#out - */ - @Override - public void flush() throws IOException { - out.flush(); - } - - /** - * Closes this output stream and releases any system resources - * associated with the stream. - *

- * The close method of FilterOutputStream - * calls its flush method, and then calls the - * close method of its underlying output stream. - * - * @exception IOException if an I/O error occurs. - * @see java.io.FilterOutputStream#flush() - * @see java.io.FilterOutputStream#out - */ - @Override - public void close() throws IOException { - deflater.finish(); - processAllData(); - - try { - flush(); - } catch (IOException ignored) { - } - out.close(); - } -} --- a/src/com/kitfox/svg/xml/cpx/CPXTest.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * SVG Salamander - * Copyright (c) 2004, Mark McKay - * All rights reserved. - * - * 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. - * - * 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 HOLDER 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. - * - * Mark McKay can be contacted at mark@kitfox.com. Salamander and other - * projects can be found at http://www.kitfox.com - * - * Created on February 12, 2004, 2:45 PM - */ - -package com.kitfox.svg.xml.cpx; - -import com.kitfox.svg.SVGConst; -import java.io.*; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * @author Mark McKay - * @author Mark McKay - */ -public class CPXTest { - - /** Creates a new instance of CPXTest */ - public CPXTest() { - -// FileInputStream fin = new FileInputStream(); - writeTest(); - readTest(); - } - - public void writeTest() - { - try { - - InputStream is = CPXTest.class.getResourceAsStream("/data/readme.txt"); -//System.err.println("Is " + is); - - FileOutputStream fout = new FileOutputStream("C:\\tmp\\cpxFile.cpx"); - CPXOutputStream cout = new CPXOutputStream(fout); - - byte[] buffer = new byte[1024]; - int numBytes; - while ((numBytes = is.read(buffer)) != -1) - { - cout.write(buffer, 0, numBytes); - } - cout.close(); - } - catch (Exception e) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, null, e); - } - } - - public void readTest() - { - try { - -// InputStream is = CPXTest.class.getResourceAsStream("/rawdata/test/cpx/text.txt"); -// InputStream is = CPXTest.class.getResourceAsStream("/rawdata/test/cpx/cpxFile.cpx"); - FileInputStream is = new FileInputStream("C:\\tmp\\cpxFile.cpx"); - CPXInputStream cin = new CPXInputStream(is); - - BufferedReader br = new BufferedReader(new InputStreamReader(cin)); - String line; - while ((line = br.readLine()) != null) - { - System.err.println(line); - } - } - catch (Exception e) - { - Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, null, e); - } - } - - /** - * @param args the command line arguments - */ - public static void main(String[] args) - { - new CPXTest(); - } - -} --- /dev/null +++ b/src/com/github/weisj/jsvg/SVGDocument.java @@ -0,0 +1,178 @@ +/* + * MIT License + * + * Copyright (c) 2021-2026 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg; + +import java.awt.*; +import java.awt.geom.AffineTransform; +import java.awt.geom.Area; +import java.awt.geom.Path2D; + +import javax.swing.*; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import com.github.weisj.jsvg.attributes.PreserveAspectRatio; +import com.github.weisj.jsvg.attributes.font.SVGFont; +import com.github.weisj.jsvg.nodes.SVG; +import com.github.weisj.jsvg.paint.SVGPaint; +import com.github.weisj.jsvg.parser.impl.DocumentConstructorAccessor; +import com.github.weisj.jsvg.renderer.*; +import com.github.weisj.jsvg.renderer.MeasureContext; +import com.github.weisj.jsvg.renderer.NullPlatformSupport; +import com.github.weisj.jsvg.renderer.PlatformSupport; +import com.github.weisj.jsvg.renderer.animation.Animation; +import com.github.weisj.jsvg.renderer.animation.AnimationState; +import com.github.weisj.jsvg.renderer.awt.AwtComponentPlatformSupport; +import com.github.weisj.jsvg.renderer.impl.*; +import com.github.weisj.jsvg.renderer.impl.context.RenderContextAccessor; +import com.github.weisj.jsvg.renderer.output.Output; +import com.github.weisj.jsvg.renderer.output.impl.CurrentColorProvider; +import com.github.weisj.jsvg.renderer.output.impl.ShapeOutput; +import com.github.weisj.jsvg.view.FloatSize; +import com.github.weisj.jsvg.view.ViewBox; + +public final class SVGDocument { + private static final boolean DEBUG = false; + private final @NotNull SVG root; + private final @NotNull FloatSize size; + + static { + DocumentConstructorAccessor.setDocumentConstructor(SVGDocument::new); + } + + private SVGDocument(@NotNull SVG root) { + this.root = root; + this.size = sizeForViewport(null); + } + + public @NotNull FloatSize size() { + return size; + } + + public @NotNull FloatSize sizeForViewport(@Nullable ViewBox viewport) { + float em = SVGFont.defaultFontSize(); + return root.sizeForTopLevel(viewport, em, SVGFont.exFromEm(em)); + } + + public @NotNull ViewBox viewBox() { + return root.staticViewBox(size()); + } + + public @NotNull Shape computeShape() { + return computeShape(null); + } + + public @NotNull Shape computeShape(@Nullable ViewBox viewBox) { + Area accumulator = new Area(new Path2D.Float()); + renderWithPlatform(NullPlatformSupport.INSTANCE, new ShapeOutput(accumulator), viewBox); + return accumulator; + } + + public boolean isAnimated() { + return animation().duration() > 0; + } + + public @NotNull Animation animation() { + return root.animationPeriod(); + } + + public void render(@Nullable JComponent component, @NotNull Graphics2D g) { + render(component, g, null); + } + + public void render(@Nullable Component component, @NotNull Graphics2D graphics2D, @Nullable ViewBox bounds) { + PlatformSupport platformSupport = component != null + ? new AwtComponentPlatformSupport(component) + : NullPlatformSupport.INSTANCE; + renderWithPlatform(platformSupport, graphics2D, bounds); + } + + private float computePlatformFontSize(@NotNull PlatformSupport platformSupport, @NotNull Output output) { + return output.contextFontSize().orElseGet(platformSupport::fontSize); + } + + public void renderWithPlatform(@NotNull PlatformSupport platformSupport, @NotNull Graphics2D graphics2D, + @Nullable ViewBox bounds) { + Output output = Output.createForGraphics(graphics2D); + renderWithPlatform(platformSupport, output, bounds); + output.dispose(); + } + + public void renderWithPlatform(@NotNull PlatformSupport platformSupport, @NotNull Output output, + @Nullable ViewBox viewportBounds) { + renderWithPlatform(platformSupport, output, viewportBounds, null); + } + + public void renderWithPlatform(@NotNull PlatformSupport platformSupport, @NotNull Output output, + @Nullable ViewBox viewportBounds, @Nullable AnimationState animationState) { + RenderContext context = prepareRenderContext(platformSupport, output, viewportBounds, animationState); + + ViewBox rootVieBox = new ViewBox(root.size(context)); + + if (viewportBounds == null) viewportBounds = rootVieBox; + + if (DEBUG) { + final ViewBox finalBounds = viewportBounds; + output.debugPaint(g -> { + g.setColor(Color.RED); + g.draw(finalBounds); + }); + } + + AffineTransform rootTransform = PreserveAspectRatio.forDisplay() + .computeViewportTransform(viewportBounds.size(), rootVieBox); + + RenderContext innerContext = NodeRenderer.setupInnerViewRenderContext(rootVieBox, context, true); + + output.applyClip(viewportBounds); + + innerContext.translate(output, viewportBounds.location()); + innerContext.transform(output, rootTransform); + + // Needed for vector-effects to work properly. + RenderContextAccessor.Accessor accessor = RenderContextAccessor.instance(); + accessor.setRootTransform(innerContext, output.transform()); + + NodeRenderer.renderRootSVG(root, context, output); + } + + private @NotNull RenderContext prepareRenderContext( + @NotNull PlatformSupport platformSupport, + @NotNull Output output, + @Nullable ViewBox viewportBounds, + @Nullable AnimationState animationState) { + float defaultEm = computePlatformFontSize(platformSupport, output); + float defaultEx = SVGFont.exFromEm(defaultEm); + AnimationState animState = animationState != null ? animationState : AnimationState.NO_ANIMATION; + MeasureContext initialMeasure = viewportBounds != null + ? MeasureContext.createInitial(viewportBounds.size(), defaultEm, defaultEx, animState) + : MeasureContext.createInitial(root.sizeForTopLevel(null, defaultEm, defaultEx), + defaultEm, defaultEx, animState); + SVGPaint currentColor = null; + if (output instanceof CurrentColorProvider) { + currentColor = ((CurrentColorProvider) output).currentColor(); + } + return RenderContextAccessor.instance().createInitial(currentColor, platformSupport, initialMeasure); + } + +} --- /dev/null +++ b/src/com/github/weisj/jsvg/animation/Additive.java @@ -0,0 +1,27 @@ +/* + * MIT License + * + * Copyright (c) 2024 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.animation; + +public enum Additive { + SUM, + REPLACE; +} --- /dev/null +++ b/src/com/github/weisj/jsvg/animation/AnimationPeriod.java @@ -0,0 +1,81 @@ +/* + * MIT License + * + * Copyright (c) 2024-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.animation; + +import java.util.List; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import com.github.weisj.jsvg.animation.time.Interval; +import com.github.weisj.jsvg.renderer.animation.Animation; + +public final class AnimationPeriod implements Animation { + private final long start; + private final long end; + private final boolean freeze; + + public AnimationPeriod(long start, long end, boolean freeze) { + this.start = start; + this.end = end; + this.freeze = freeze; + } + + public @NotNull AnimationPeriod derive(@Nullable Track track) { + if (track == null) return this; + + + // Compute the begin and total duration + List<@NotNull Interval> intervals = track.intervals(); + float repeatCount = track.repeatCount(); + long intervalsBegin = intervals.get(0).begin().milliseconds(); + Interval lastInterval = intervals.get(intervals.size() - 1); + long intervalsEnd = + (long) (lastInterval.begin().milliseconds() + repeatCount * lastInterval.duration().milliseconds()); + + long animationStartTime = Math.min(this.start, intervalsBegin); + long animationEndTime; + if (Float.isFinite(repeatCount)) { + animationEndTime = Math.max(this.end, intervalsEnd); + } else { + animationEndTime = Long.MAX_VALUE; + } + + boolean animationFreezes = this.freeze || track.fill() == Fill.FREEZE; + return new AnimationPeriod(animationStartTime, animationEndTime, animationFreezes); + } + + @Override + public long duration() { + return end - start; + } + + @Override + public long startTime() { + return start; + } + + @Override + public long endTime() { + return end; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/animation/AnimationValuesType.java @@ -0,0 +1,36 @@ +/* + * MIT License + * + * Copyright (c) 2024 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.animation; + + +public enum AnimationValuesType { + VALUES, + FROM_TO, + FROM_BY, + BY, + TO; + + public boolean endIsBy() { + return this == FROM_BY || this == BY; + } + +} --- /dev/null +++ b/src/com/github/weisj/jsvg/animation/Fill.java @@ -0,0 +1,30 @@ +/* + * MIT License + * + * Copyright (c) 2024 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.animation; + +import com.github.weisj.jsvg.attributes.Default; + +public enum Fill { + @Default + REMOVE, + FREEZE +} --- /dev/null +++ b/src/com/github/weisj/jsvg/animation/Track.java @@ -0,0 +1,202 @@ +/* + * MIT License + * + * Copyright (c) 2024-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.animation; + +import java.util.*; +import java.util.stream.Collectors; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import com.github.weisj.jsvg.animation.interpolation.*; +import com.github.weisj.jsvg.animation.time.Duration; +import com.github.weisj.jsvg.animation.time.Interval; +import com.github.weisj.jsvg.parser.impl.AttributeNode; +import com.github.weisj.jsvg.parser.impl.SeparatorMode; + +public final class Track { + private final @NotNull List<@NotNull Interval> intervals; + private final float repeatCount; + private final Fill fill; + private final DefaultInterpolator interpolator; + + private Track(@NotNull List<@NotNull Interval> intervals, float repeatCount, Fill fill, + AnimationValuesType valuesType, Additive additive) { + this.intervals = intervals; + this.repeatCount = repeatCount; + this.fill = fill; + this.interpolator = new DefaultInterpolator(valuesType, additive); + } + + public static @Nullable Track parse(@NotNull AttributeNode attributeNode, + @NotNull AnimationValuesType valuesType, @NotNull Additive additive) { + List begins = parseBegin(attributeNode); + Duration duration = attributeNode.getDuration("dur", Duration.INDEFINITE); + + List intervals = begins.stream() + .map(b -> new Interval(b, b.plus(duration))) + .filter(Interval::isValid) + .sorted(Comparator.comparing(Interval::begin)) + .collect(Collectors.toList()); + + String repeatCountStr = attributeNode.getValue("repeatCount"); + float repeatCount; + if ("indefinite".equals(repeatCountStr)) { + repeatCount = Float.POSITIVE_INFINITY; + } else { + repeatCount = attributeNode.parser().parseFloat(repeatCountStr, 1); + } + if (intervals.isEmpty() || repeatCount <= 0) { + return null; + } + + return new Track(intervals, repeatCount, attributeNode.getEnum("fill", Fill.REMOVE), + valuesType, additive); + } + + @NotNull + private static List parseBegin(@NotNull AttributeNode attributeNode) { + String[] beginsRaw = attributeNode.getStringList("begin", SeparatorMode.SEMICOLON_ONLY); + List begins; + + if (beginsRaw.length > 0) { + begins = new ArrayList<>(beginsRaw.length); + for (String s : beginsRaw) { + Duration b = attributeNode.parser().parseDuration(s, null); + if (b != null) begins.add(b); + } + } else { + begins = Collections.singletonList(Duration.ZERO); + } + return begins; + } + + public @NotNull List<@NotNull Interval> intervals() { + return intervals; + } + + public float repeatCount() { + return repeatCount; + } + + public @NotNull Fill fill() { + return fill; + } + + private int iterationCount(@NotNull Duration duration, long timestampMillis) { + long durationMillis = duration.milliseconds(); + return (int) (timestampMillis / durationMillis); + } + + private float iterationProgress(@NotNull Duration duration, long timestampMillis) { + long durationMillis = duration.milliseconds(); + return (float) (timestampMillis % durationMillis) / durationMillis; + } + + private @Nullable Interval currentInterval(long timestamp) { + ListIterator<@NotNull Interval> iterator = intervals.listIterator(intervals.size()); + while (iterator.hasPrevious()) { + Interval interval = iterator.previous(); + if (interval.end().milliseconds() <= timestamp) { + return interval; + } + } + return null; + } + + public @NotNull InterpolationProgress interpolationProgress(long timestamp, int valueCount) { + if (valueCount == 0) return InterpolationProgress.INITIAL; + Interval currentInterval = currentInterval(timestamp); + if (currentInterval == null) return InterpolationProgress.INITIAL; + + long time = timestamp - currentInterval.begin().milliseconds(); + Duration duration = currentInterval.duration(); + int iterationCount = iterationCount(duration, time); + float iterationProgress = iterationProgress(duration, time); + float totalIteration = iterationCount + iterationProgress; + + if (totalIteration > repeatCount) { + if (fill == Fill.FREEZE) { + return new InterpolationProgress(valueCount - 1, 0); + } else { + return InterpolationProgress.INITIAL; + } + } + + int i = (int) Math.floor(iterationProgress * (valueCount - 1)); + float t = (valueCount - 1) * iterationProgress - i; + return new InterpolationProgress(i, t); + } + + public @NotNull FloatInterpolator floatInterpolator() { + return interpolator; + } + + public @NotNull FloatListInterpolator floatListInterpolator() { + return interpolator; + } + + public @NotNull PaintInterpolator paintInterpolator() { + return interpolator; + } + + public @NotNull TransformInterpolator transformInterpolator() { + return interpolator; + } + + public static final class InterpolationProgress { + public static final InterpolationProgress INITIAL = new InterpolationProgress(-1, 0); + + private final int iterationIndex; + private final float indexProgress; + + public InterpolationProgress(int iterationIndex, float indexProgress) { + this.iterationIndex = iterationIndex; + this.indexProgress = indexProgress; + } + + public boolean isInitial() { + return iterationIndex == -1; + } + + public int iterationIndex() { + return iterationIndex; + } + + public float indexProgress() { + return indexProgress; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + InterpolationProgress that = (InterpolationProgress) o; + return iterationIndex == that.iterationIndex && Float.compare(indexProgress, that.indexProgress) == 0; + } + + @Override + public int hashCode() { + return Objects.hash(iterationIndex, indexProgress); + } + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/animation/interpolation/DefaultInterpolator.java @@ -0,0 +1,242 @@ +/* + * MIT License + * + * Copyright (c) 2024-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.animation.interpolation; + +import static com.github.weisj.jsvg.geometry.util.GeometryUtil.lerp; + +import java.awt.*; +import java.awt.geom.AffineTransform; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import com.github.weisj.jsvg.animation.Additive; +import com.github.weisj.jsvg.animation.AnimationValuesType; +import com.github.weisj.jsvg.attributes.transform.TransformPart; +import com.github.weisj.jsvg.attributes.value.TransformValue; +import com.github.weisj.jsvg.geometry.util.GeometryUtil; +import com.github.weisj.jsvg.paint.SVGPaint; +import com.github.weisj.jsvg.paint.SimplePaintSVGPaint; +import com.github.weisj.jsvg.paint.impl.AwtSVGPaint; +import com.github.weisj.jsvg.paint.impl.RGBColor; +import com.github.weisj.jsvg.renderer.MeasureContext; + +public final class DefaultInterpolator + implements FloatInterpolator, FloatListInterpolator, PaintInterpolator, TransformInterpolator { + private final Additive additive; + private final AnimationValuesType valuesType; + + public DefaultInterpolator(AnimationValuesType valuesType, Additive additive) { + this.valuesType = valuesType; + this.additive = additive; + } + + @Override + public float interpolate(float initial, float a, float b, float progress) { + switch (valuesType) { + case FROM_BY: { + return a + b * progress; + } + case BY: { + return initial + b * progress; + } + case TO: { + return initial + (b - initial) * progress; + } + case FROM_TO: + case VALUES: + default: { + float result = a + (b - a) * progress; + + if (additive == Additive.SUM) { + result += initial; + } + return result; + } + } + } + + private static float @NotNull [] ensureCacheCapacity(float @Nullable [] cache, int length) { + if (cache == null || cache.length != length) { + return new float[length]; + } + return cache; + } + + private static float @NotNull [] arrayLerp(float @Nullable [] cache, float @NotNull [] from, float @Nullable [] to, + float progress) { + float t = progress; + + boolean isEndTime = GeometryUtil.approximatelyEqual(t, 1); + if (to == null || (from.length != to.length && !isEndTime)) { + // Use discrete animation + t = 0; + } + + float[] result = cache; + if (to == null || GeometryUtil.approximatelyEqual(t, 0)) { + result = ensureCacheCapacity(result, from.length); + System.arraycopy(from, 0, result, 0, from.length); + } else if (isEndTime) { + result = ensureCacheCapacity(result, to.length); + System.arraycopy(to, 0, result, 0, to.length); + } else { + result = ensureCacheCapacity(result, from.length); + for (int i = 0; i < from.length; i++) { + result[i] = lerp(t, from[i], to[i]); + } + } + return result; + } + + /** + * This method is used to calculate the result of the following operation: result_i = a * x_i + b_i + *

    + *
  • If b_i is shorter than a_i, b_i is repeated. + *
  • If b_i is longer than a_i, the extra values are ignored. + *
+ */ + private static float @NotNull [] saxpy(float @Nullable [] cache, float @NotNull [] b, float @Nullable [] x, + float a) { + float[] result = ensureCacheCapacity(cache, b.length); + System.arraycopy(b, 0, result, 0, b.length); + + if (x == null) return b; + + int n = Math.min(result.length, x.length); + for (int i = 0; i < n; i++) { + result[i] += a * x[i]; + } + for (int i = n; i < result.length; i++) { + result[i] += a * x[i % n]; + } + return result; + } + + @Override + public float @NotNull [] interpolate(float @NotNull [] initial, float @NotNull [] a, float @Nullable [] b, + float progress, float @Nullable [] cache) { + switch (valuesType) { + case FROM_BY: { + return saxpy(cache, a, b, progress); + } + case BY: { + return saxpy(cache, initial, b, progress); + } + case TO: { + return arrayLerp(cache, initial, b, progress); + } + case FROM_TO: + case VALUES: + default: { + float[] result = arrayLerp(cache, a, b, progress); + + if (additive == Additive.SUM) { + result = saxpy(result, result, initial, 1); + } + return result; + } + } + } + + private static @Nullable RGBColor extractColor(@NotNull SVGPaint p) { + if (!(p instanceof SimplePaintSVGPaint)) return null; + Paint paint = ((SimplePaintSVGPaint) p).paint(); + if (paint instanceof Color) return new RGBColor((Color) paint); + if (paint instanceof RGBColor) return (RGBColor) paint; + return null; + } + + @Override + public @NotNull SVGPaint interpolate(@NotNull SVGPaint initial, @NotNull SVGPaint a, @NotNull SVGPaint b, + float progress) { + RGBColor colorA = extractColor(a); + RGBColor colorB = extractColor(b); + + if (colorA == null || colorB == null) { + return discreteAnimation(initial, a, b, progress); + } + + switch (valuesType) { + case FROM_BY: { + return new AwtSVGPaint(RGBColor.saxpy(progress, colorA, colorB)); + } + case BY: { + RGBColor initialColor = extractColor(initial); + if (initialColor == null) return initial; + return new AwtSVGPaint(RGBColor.saxpy(progress, initialColor, colorB)); + } + case TO: { + RGBColor initialColor = extractColor(initial); + if (initialColor == null) return initial; + return new AwtSVGPaint(RGBColor.interpolate(progress, initialColor, colorB)); + } + case FROM_TO: + case VALUES: + default: { + RGBColor result = RGBColor.interpolate(progress, colorA, colorB); + + if (additive == Additive.SUM) { + RGBColor initialColor = extractColor(initial); + if (initialColor == null) return initial; + result = RGBColor.add(initialColor, result); + } + return new AwtSVGPaint(result); + } + } + } + + private SVGPaint discreteAnimation(@NotNull SVGPaint initial, @NotNull SVGPaint a, @NotNull SVGPaint b, + float progress) { + if (additive != Additive.REPLACE) { + return initial; + } + return GeometryUtil.approximatelyEqual(progress, 1) ? b : a; + } + + @Override + public @NotNull AffineTransform interpolate(@NotNull MeasureContext context, @NotNull TransformValue initial, + @NotNull TransformPart a, @NotNull TransformPart b, float progress) { + switch (valuesType) { + case FROM_BY: { + return b.applyToTransform(a.applyToTransform(new AffineTransform(), context), context, progress); + } + case BY: { + return b.applyToTransform(initial.get(context), context, progress); + } + case TO: { + // NOTE: This is undefined by the specification + return GeometryUtil.interpolate(initial.get(context), b.toTransform(context), progress); + } + case FROM_TO: + case VALUES: + default: { + AffineTransform result = TransformPart.interpolate(a, b, context, progress); + + if (additive == Additive.SUM) { + result.preConcatenate(initial.get(context)); + } + return result; + } + } + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/animation/interpolation/FloatInterpolator.java @@ -0,0 +1,27 @@ +/* + * MIT License + * + * Copyright (c) 2024 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.animation.interpolation; + +public interface FloatInterpolator { + + float interpolate(float initial, float a, float b, float progress); +} --- /dev/null +++ b/src/com/github/weisj/jsvg/animation/interpolation/FloatListInterpolator.java @@ -0,0 +1,31 @@ +/* + * MIT License + * + * Copyright (c) 2024 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.animation.interpolation; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public interface FloatListInterpolator { + + float @NotNull [] interpolate(float @NotNull [] initial, float @NotNull [] a, float @Nullable [] b, + float progress, float @Nullable [] cache); +} --- /dev/null +++ b/src/com/github/weisj/jsvg/animation/interpolation/PaintInterpolator.java @@ -0,0 +1,32 @@ +/* + * MIT License + * + * Copyright (c) 2024-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.animation.interpolation; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.paint.SVGPaint; + +public interface PaintInterpolator { + + @NotNull + SVGPaint interpolate(@NotNull SVGPaint initial, @NotNull SVGPaint a, @NotNull SVGPaint b, float progress); +} --- /dev/null +++ b/src/com/github/weisj/jsvg/animation/interpolation/TransformInterpolator.java @@ -0,0 +1,37 @@ +/* + * MIT License + * + * Copyright (c) 2024-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.animation.interpolation; + +import java.awt.geom.AffineTransform; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.attributes.transform.TransformPart; +import com.github.weisj.jsvg.attributes.value.TransformValue; +import com.github.weisj.jsvg.renderer.MeasureContext; + +public interface TransformInterpolator { + + @NotNull + AffineTransform interpolate(@NotNull MeasureContext context, + @NotNull TransformValue initial, @NotNull TransformPart a, @NotNull TransformPart b, float progress); +} --- /dev/null +++ b/src/com/github/weisj/jsvg/animation/interpolation/package-info.java @@ -0,0 +1,3 @@ +@org.osgi.annotation.bundle.Export(attribute = "x-internal") +@aQute.bnd.annotation.jpms.ExportTo("com.github.weisj.jsvg.javafx") +package com.github.weisj.jsvg.animation.interpolation; --- /dev/null +++ b/src/com/github/weisj/jsvg/animation/package-info.java @@ -0,0 +1,3 @@ +@org.osgi.annotation.bundle.Export(attribute = "x-internal") +@aQute.bnd.annotation.jpms.ExportTo("com.github.weisj.jsvg.javafx") +package com.github.weisj.jsvg.animation; --- /dev/null +++ b/src/com/github/weisj/jsvg/animation/time/Duration.java @@ -0,0 +1,84 @@ +/* + * MIT License + * + * Copyright (c) 2024-2026 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.animation.time; + +import java.util.Objects; + +import org.jetbrains.annotations.NotNull; + +import com.google.errorprone.annotations.Immutable; + +@Immutable +public final class Duration implements Comparable { + public static final long INDEFINITE_RAW = Long.MAX_VALUE; + public static final @NotNull Duration INDEFINITE = new Duration(INDEFINITE_RAW); + public static final Duration ZERO = new Duration(0); + + private final long milliseconds; + + public Duration(long milliseconds) { + this.milliseconds = milliseconds; + } + + public long milliseconds() { + return milliseconds; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Duration duration = (Duration) o; + return milliseconds == duration.milliseconds; + } + + @Override + public int hashCode() { + return Objects.hash(milliseconds); + } + + public boolean isIndefinite() { + return milliseconds == INDEFINITE_RAW; + } + + public @NotNull Duration plus(@NotNull Duration duration) { + if (duration.isIndefinite() || this.isIndefinite()) return INDEFINITE; + return new Duration(milliseconds + duration.milliseconds); + } + + public @NotNull Duration minus(@NotNull Duration duration) { + if (duration.isIndefinite() || this.isIndefinite()) return INDEFINITE; + return new Duration(milliseconds - duration.milliseconds); + } + + @Override + public int compareTo(@NotNull Duration o) { + return Long.compare(milliseconds, o.milliseconds); + } + + @Override + public String toString() { + return "Duration{" + + "milliseconds=" + milliseconds + + '}'; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/animation/time/Interval.java @@ -0,0 +1,58 @@ +/* + * MIT License + * + * Copyright (c) 2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.animation.time; + +import org.jetbrains.annotations.NotNull; + +public final class Interval { + private final @NotNull Duration begin; + private final @NotNull Duration end; + + public Interval(@NotNull Duration begin, @NotNull Duration end) { + this.begin = begin; + this.end = end; + } + + public @NotNull Duration begin() { + return begin; + } + + public @NotNull Duration end() { + return begin; + } + + public @NotNull Duration duration() { + return end.minus(begin); + } + + @Override + public String toString() { + return "Interval{" + + "begin=" + begin + + ", end=" + end + + '}'; + } + + public boolean isValid() { + return !begin.isIndefinite() && !end.isIndefinite() && begin.milliseconds() < end.milliseconds(); + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/animation/time/TimeUnit.java @@ -0,0 +1,61 @@ +/* + * MIT License + * + * Copyright (c) 2021-2024 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.animation.time; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.attributes.SuffixUnit; + + +public enum TimeUnit implements SuffixUnit { + Hour(60 * 60 * 1000L, "h"), + Minute(60 * 1000L, "min"), + Second(1000L, "s"), + Millisecond(1L, "ms"), + Raw(1000L, ""); // Same as seconds + + private static final TimeUnit[] units = values(); + + @Override + public @NotNull TimeUnit @NotNull [] units() { + return units; + } + + private final @NotNull String suffix; + private final long milliseconds; + + TimeUnit(long milliseconds, @NotNull String suffix) { + this.suffix = suffix; + this.milliseconds = milliseconds; + } + + @Override + public @NotNull Duration valueOf(float value) { + if (value == 0) return new Duration(0); + return new Duration((long) (this.milliseconds * value)); + } + + @Override + public @NotNull String suffix() { + return suffix; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/animation/time/package-info.java @@ -0,0 +1,3 @@ +@org.osgi.annotation.bundle.Export(attribute = "x-internal") +@aQute.bnd.annotation.jpms.ExportTo("com.github.weisj.jsvg.javafx") +package com.github.weisj.jsvg.animation.time; --- /dev/null +++ b/src/com/github/weisj/jsvg/animation/value/AnimatedColor.java @@ -0,0 +1,122 @@ +/* + * MIT License + * + * Copyright (c) 2024-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.animation.value; + +import java.awt.*; +import java.awt.geom.Rectangle2D; +import java.util.Objects; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import com.github.weisj.jsvg.animation.Track; +import com.github.weisj.jsvg.attributes.value.ColorValue; +import com.github.weisj.jsvg.paint.SVGPaint; +import com.github.weisj.jsvg.paint.SimplePaintSVGPaint; +import com.github.weisj.jsvg.paint.impl.RGBColor; +import com.github.weisj.jsvg.renderer.MeasureContext; +import com.github.weisj.jsvg.renderer.RenderContext; +import com.github.weisj.jsvg.renderer.output.Output; + +public final class AnimatedColor implements SVGPaint, ColorValue { + + private final @NotNull Track track; + private final @NotNull ColorValue initial; + private final @NotNull RGBColor @NotNull [] values; + + private Color current; + private long currentTimestamp = -1; + + public AnimatedColor(@NotNull Track track, @NotNull ColorValue initial, @NotNull RGBColor @NotNull [] values) { + this.track = track; + this.initial = initial; + this.values = values; + } + + public @NotNull AnimatedColor derive(@NotNull SVGPaint value) { + if (this.initial != RGBColor.INHERITED) return this; + ColorValue c = null; + if (value instanceof ColorValue) { + c = (ColorValue) value; + } else if (value instanceof SimplePaintSVGPaint) { + Paint p = ((SimplePaintSVGPaint) value).paint(); + if (p instanceof Color) { + c = new RGBColor((Color) p); + } else if (p instanceof RGBColor) { + c = (RGBColor) p; + } + } else { + c = RGBColor.DEFAULT; + } + if (c == null) return this; + return new AnimatedColor(track, c, values); + } + + @Override + public @NotNull Color get(@NotNull MeasureContext context) { + return current(context); + } + + private @NotNull Color current(@NotNull MeasureContext context) { + long timestamp = context.timestamp(); + if (currentTimestamp == timestamp) return current; + currentTimestamp = timestamp; + current = computeCurrent(context, timestamp); + return current; + } + + private @NotNull Color computeCurrent(@NotNull MeasureContext context, long timestamp) { + Track.InterpolationProgress progress = track.interpolationProgress(timestamp, values.length); + if (progress.isInitial()) return Objects.requireNonNull(initial).get(context); + int i = progress.iterationIndex(); + + assert i >= 0; + assert values.length > 0; + if (i >= values.length - 1) { + return values[values.length - 1].toColor(); + } + + RGBColor start = values[i]; + RGBColor end = values[i + 1]; + float t = progress.indexProgress(); + return RGBColor.interpolate(t, start, end).toColor(); + } + + @Override + public void fillShape(@NotNull Output output, @NotNull RenderContext context, @NotNull Shape shape, + @Nullable Rectangle2D bounds) { + output.setPaint(current(context.measureContext())); + output.fillShape(shape); + } + + @Override + public void drawShape(@NotNull Output output, @NotNull RenderContext context, @NotNull Shape shape, + @Nullable Rectangle2D bounds) { + output.setPaint(current(context.measureContext())); + output.drawShape(shape); + } + + @Override + public boolean isVisible(@NotNull RenderContext context) { + return RGBColor.isVisible(current(context.measureContext())); + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/animation/value/AnimatedFloat.java @@ -0,0 +1,61 @@ +/* + * MIT License + * + * Copyright (c) 2024-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.animation.value; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.animation.Track; +import com.github.weisj.jsvg.attributes.value.FloatValue; +import com.github.weisj.jsvg.renderer.MeasureContext; + +public final class AnimatedFloat implements FloatValue { + + private final @NotNull Track track; + private final @NotNull FloatValue initial; + private final float @NotNull [] values; + + AnimatedFloat(@NotNull Track track, @NotNull FloatValue initial, float @NotNull [] values) { + this.track = track; + this.initial = initial; + this.values = values; + } + + @Override + public float get(@NotNull MeasureContext context) { + long timestamp = context.timestamp(); + Track.InterpolationProgress progress = track.interpolationProgress(timestamp, values.length); + + if (progress.isInitial()) return initial.get(context); + int i = progress.iterationIndex(); + + assert i >= 0; + assert values.length > 0; + if (i >= values.length - 1) { + return values[i]; + } + + float start = values[i]; + float end = values[i + 1]; + + return track.floatInterpolator().interpolate(initial.get(context), start, end, progress.indexProgress()); + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/animation/value/AnimatedFloatList.java @@ -0,0 +1,83 @@ +/* + * MIT License + * + * Copyright (c) 2024-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.animation.value; + + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.animation.Track; +import com.github.weisj.jsvg.attributes.value.FloatListValue; +import com.github.weisj.jsvg.renderer.MeasureContext; + +public final class AnimatedFloatList implements FloatListValue { + + private final @NotNull Track track; + + private final @NotNull FloatListValue initial; + private final float @NotNull [] @NotNull [] values; + private float[] cache; + + private long timestamp = 0; + private Track.InterpolationProgress progressCacheKey = null; + + public AnimatedFloatList(@NotNull Track track, @NotNull FloatListValue initial, + float @NotNull [] @NotNull [] values) { + this.track = track; + this.initial = initial; + this.values = values; + } + + public @NotNull FloatListValue initial() { + return initial; + } + + public boolean isDirty(long timestamp) { + return this.timestamp != timestamp; + } + + @Override + public float @NotNull [] get(@NotNull MeasureContext context) { + long ts = context.timestamp(); + if (ts != this.timestamp) { + this.timestamp = ts; + Track.InterpolationProgress progress = track.interpolationProgress(ts, values.length); + + if (progress.equals(progressCacheKey)) { + return cache; + } + progressCacheKey = progress; + + if (progress.isInitial()) { + cache = initial.get(context); + return cache; + } + + int index = progress.iterationIndex(); + float[] start = values[index]; + float[] end = index == values.length - 1 ? null : values[index + 1]; + + float fraction = progress.indexProgress(); + cache = track.floatListInterpolator().interpolate(initial.get(context), start, end, fraction, cache); + } + return cache; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/animation/value/AnimatedLength.java @@ -0,0 +1,93 @@ +/* + * MIT License + * + * Copyright (c) 2024-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.animation.value; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.animation.Track; +import com.github.weisj.jsvg.attributes.value.LengthValue; +import com.github.weisj.jsvg.geometry.size.Length; +import com.github.weisj.jsvg.renderer.MeasureContext; + +public final class AnimatedLength implements LengthValue { + private final @NotNull Track track; + private final @NotNull LengthValue initial; + private final @NotNull Length @NotNull [] values; + + public AnimatedLength(@NotNull Track track, + @NotNull LengthValue initial, @NotNull Length @NotNull [] values) { + this.track = track; + this.initial = initial; + this.values = values; + } + + public @NotNull AnimatedLength derive(@NotNull LengthValue initialValue) { + if (this.initial != Length.INHERITED) return this; + return new AnimatedLength(track, initialValue, values); + } + + public @NotNull LengthValue initial() { + return initial; + } + + @Override + public float resolve(@NotNull MeasureContext context) { + long timestamp = context.timestamp(); + Track.InterpolationProgress progress = track.interpolationProgress(timestamp, values.length); + + if (progress.isInitial()) return initial.resolve(context); + int i = progress.iterationIndex(); + + assert i >= 0; + assert values.length > 0; + if (i >= values.length - 1) { + return values[values.length - 1].resolve(context); + } + + float start = values[i].resolve(context); + float end = values[i + 1].resolve(context); + + return track.floatInterpolator().interpolate( + initial.resolve(context), + start, end, progress.indexProgress()); + } + + @Override + public boolean isConstantlyZero() { + for (Length value : values) { + if (!value.isConstantlyZero()) { + return false; + } + } + return initial.isConstantlyZero(); + } + + @Override + public boolean isConstantlyNonNegative() { + for (Length value : values) { + if (!value.isConstantlyNonNegative()) { + return false; + } + } + return initial.isConstantlyNonNegative(); + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/animation/value/AnimatedPaint.java @@ -0,0 +1,98 @@ +/* + * MIT License + * + * Copyright (c) 2024-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.animation.value; + +import java.awt.*; +import java.awt.geom.Rectangle2D; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import com.github.weisj.jsvg.animation.Track; +import com.github.weisj.jsvg.paint.SVGPaint; +import com.github.weisj.jsvg.paint.impl.PredefinedPaints; +import com.github.weisj.jsvg.renderer.MeasureContext; +import com.github.weisj.jsvg.renderer.RenderContext; +import com.github.weisj.jsvg.renderer.output.Output; + +public class AnimatedPaint implements SVGPaint { + + private final @NotNull Track track; + private final @NotNull SVGPaint initial; + private final @NotNull SVGPaint @NotNull [] values; + + private SVGPaint current; + private long currentTimestamp = -1; + + public AnimatedPaint(@NotNull Track track, @NotNull SVGPaint initial, @NotNull SVGPaint @NotNull [] values) { + this.track = track; + this.initial = initial; + this.values = values; + } + + public @NotNull AnimatedPaint derive(@NotNull SVGPaint initialValue) { + if (this.initial != PredefinedPaints.INHERITED) return this; + return new AnimatedPaint(track, initialValue, values); + } + + private @NotNull SVGPaint current(@NotNull MeasureContext context) { + long timestamp = context.timestamp(); + if (currentTimestamp == timestamp) return current; + currentTimestamp = timestamp; + current = computeCurrent(timestamp); + return current; + } + + private @NotNull SVGPaint computeCurrent(long timestamp) { + Track.InterpolationProgress progress = track.interpolationProgress(timestamp, values.length); + if (progress.isInitial()) return initial; + int i = progress.iterationIndex(); + + assert i >= 0; + assert values.length > 0; + if (i >= values.length - 1) { + return values[values.length - 1]; + } + + SVGPaint start = values[i]; + SVGPaint end = values[i + 1]; + + return track.paintInterpolator().interpolate(initial, start, end, progress.indexProgress()); + } + + @Override + public void fillShape(@NotNull Output output, @NotNull RenderContext context, @NotNull Shape shape, + @Nullable Rectangle2D bounds) { + current(context.measureContext()).fillShape(output, context, shape, bounds); + } + + @Override + public void drawShape(@NotNull Output output, @NotNull RenderContext context, @NotNull Shape shape, + @Nullable Rectangle2D bounds) { + current(context.measureContext()).drawShape(output, context, shape, bounds); + } + + @Override + public boolean isVisible(@NotNull RenderContext context) { + return current(context.measureContext()).isVisible(context); + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/animation/value/AnimatedPath.java @@ -0,0 +1,51 @@ +/* + * MIT License + * + * Copyright (c) 2024-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.animation.value; + +import java.awt.geom.Path2D; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import com.github.weisj.jsvg.attributes.value.Value; +import com.github.weisj.jsvg.renderer.MeasureContext; +import com.github.weisj.jsvg.util.PathUtil; + +public final class AnimatedPath implements Value<@NotNull Path2D> { + + private final @NotNull AnimatedFloatList list; + private @Nullable Path2D cache; + private final boolean closed; + + public AnimatedPath(@NotNull AnimatedFloatList list, boolean closed) { + this.list = list; + this.closed = closed; + } + + @Override + public @NotNull Path2D get(@NotNull MeasureContext context) { + if (cache == null || list.isDirty(context.timestamp())) { + cache = PathUtil.setPolyLine(cache, list.get(context), closed); + } + return cache; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/animation/value/AnimatedPercentage.java @@ -0,0 +1,84 @@ +/* + * MIT License + * + * Copyright (c) 2024-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.animation.value; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.animation.Track; +import com.github.weisj.jsvg.attributes.value.PercentageValue; +import com.github.weisj.jsvg.geometry.size.Percentage; +import com.github.weisj.jsvg.renderer.MeasureContext; + +public final class AnimatedPercentage implements PercentageValue { + + private final @NotNull Track track; + private final @NotNull PercentageValue initial; + private final float @NotNull [] values; + private final PercentageValue multiplier; + + public AnimatedPercentage(@NotNull Track track, @NotNull PercentageValue initial, float @NotNull [] values, + PercentageValue multiplier) { + this.track = track; + this.initial = initial; + this.values = values; + this.multiplier = multiplier; + } + + public @NotNull AnimatedPercentage derive(@NotNull PercentageValue initial) { + if (this.initial != Percentage.INHERITED) return this; + return new AnimatedPercentage(track, initial, values, multiplier); + } + + @Override + public @NotNull PercentageValue multiply(@NotNull PercentageValue other) { + return new AnimatedPercentage(track, initial, values, multiplier.multiply(other)); + } + + public @NotNull PercentageValue initial() { + return initial; + } + + private float getBase(@NotNull MeasureContext context) { + long timestamp = context.timestamp(); + Track.InterpolationProgress progress = track.interpolationProgress(timestamp, values.length); + + if (progress.isInitial()) return initial.get(context); + int i = progress.iterationIndex(); + + assert i >= 0; + assert values.length > 0; + if (i >= values.length - 1) { + return values[values.length - 1]; + } + + float start = values[i]; + float end = values[i + 1]; + + return track.floatInterpolator().interpolate(initial.get(context), start, end, progress.indexProgress()); + } + + @Override + public float get(@NotNull MeasureContext context) { + return getBase(context) * multiplier.get(context); + } + +} --- /dev/null +++ b/src/com/github/weisj/jsvg/animation/value/AnimatedTransform.java @@ -0,0 +1,91 @@ +/* + * MIT License + * + * Copyright (c) 2024-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.animation.value; + +import java.awt.geom.AffineTransform; +import java.util.Objects; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.animation.Track; +import com.github.weisj.jsvg.attributes.transform.TransformPart; +import com.github.weisj.jsvg.attributes.value.ConstantLengthTransform; +import com.github.weisj.jsvg.attributes.value.TransformValue; +import com.github.weisj.jsvg.renderer.MeasureContext; + +public final class AnimatedTransform implements TransformValue { + + private final @NotNull Track track; + private final @NotNull TransformValue initial; + private final @NotNull TransformPart @NotNull [] values; + + private AffineTransform current; + private long currentTimestamp = -1; + + public AnimatedTransform(@NotNull Track track, @NotNull TransformValue initial, + @NotNull TransformPart @NotNull [] values) { + this.track = track; + this.initial = initial; + this.values = values; + } + + public @NotNull TransformValue initial() { + return initial; + } + + public @NotNull AnimatedTransform derive(@NotNull TransformValue initialValue) { + if (this.initial != ConstantLengthTransform.INHERITED) return this; + return new AnimatedTransform(track, initialValue, values); + } + + private @NotNull AffineTransform current(@NotNull MeasureContext context) { + long timestamp = context.timestamp(); + if (currentTimestamp == timestamp) return current; + currentTimestamp = timestamp; + current = computeCurrent(context, timestamp); + return current; + } + + private @NotNull AffineTransform computeCurrent(@NotNull MeasureContext context, long timestamp) { + Track.InterpolationProgress progress = track.interpolationProgress(timestamp, values.length); + if (progress.isInitial()) return Objects.requireNonNull(initial).get(context); + int i = progress.iterationIndex(); + + assert i >= 0; + assert values.length > 0; + if (i >= values.length - 1) { + AffineTransform transform = new AffineTransform(); + values[values.length - 1].applyToTransform(transform, context); + return transform; + } + + TransformPart start = values[i]; + TransformPart end = values[i + 1]; + float t = progress.indexProgress(); + return track.transformInterpolator().interpolate(context, initial, start, end, t); + } + + @Override + public @NotNull AffineTransform get(@NotNull MeasureContext context) { + return current(context); + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/animation/value/NeutralElements.java @@ -0,0 +1,38 @@ +/* + * MIT License + * + * Copyright (c) 2024-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.animation.value; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.attributes.value.*; +import com.github.weisj.jsvg.geometry.size.Length; +import com.github.weisj.jsvg.geometry.size.Percentage; + +public final class NeutralElements { + + private NeutralElements() {} + + public static final @NotNull LengthValue NEUTRAL_LENGTH = Length.ZERO; + public static final @NotNull PercentageValue NEUTRAL_PERCENTAGE = Percentage.ONE; + public static final @NotNull TransformValue NEUTRAL_TRANSFORM = ConstantLengthTransform.IDENTITY; + public static final @NotNull FloatListValue NEUTRAL_FLOAT_LIST = ConstantFloatList.EMPTY; +} --- /dev/null +++ b/src/com/github/weisj/jsvg/animation/value/package-info.java @@ -0,0 +1,3 @@ +@org.osgi.annotation.bundle.Export(attribute = "x-internal") +@aQute.bnd.annotation.jpms.ExportTo("com.github.weisj.jsvg.javafx") +package com.github.weisj.jsvg.animation.value; --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/Animatable.java @@ -0,0 +1,27 @@ +/* + * MIT License + * + * Copyright (c) 2024 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes; + +public enum Animatable { + YES, + NO +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/ColorInterpolation.java @@ -0,0 +1,42 @@ +/* + * MIT License + * + * Copyright (c) 2024 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes; + +import org.jetbrains.annotations.NotNull; + +public enum ColorInterpolation implements HasMatchName { + S_RGB("sRGB"), + LinearRGB("linearRGB"), + Auto("auto"), + Inherit("inherit"); + + private final @NotNull String matchName; + + ColorInterpolation(@NotNull String matchName) { + this.matchName = matchName; + } + + @Override + public @NotNull String matchName() { + return matchName; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/Coordinate.java @@ -0,0 +1,66 @@ +/* + * MIT License + * + * Copyright (c) 2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes; + +import java.util.Objects; + +import org.jetbrains.annotations.NotNull; + +public final class Coordinate { + private final @NotNull T x; + private final @NotNull T y; + + + public Coordinate(@NotNull T x, @NotNull T y) { + this.x = x; + this.y = y; + } + + public @NotNull T x() { + return x; + } + + public @NotNull T y() { + return y; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Coordinate that = (Coordinate) o; + return Objects.equals(x, that.x) && Objects.equals(y, that.y); + } + + @Override + public int hashCode() { + return Objects.hash(x, y); + } + + @Override + public String toString() { + return "Coordinate{" + + "x=" + x + + ", y=" + y + + '}'; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/Default.java @@ -0,0 +1,32 @@ +/* + * MIT License + * + * Copyright (c) 2021 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.FIELD) +@Retention(RetentionPolicy.SOURCE) +public @interface Default { +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/FillRule.java @@ -0,0 +1,59 @@ +/* + * MIT License + * + * Copyright (c) 2021-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes; + +import java.awt.geom.Path2D; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.parser.impl.AttributeNode; + +public enum FillRule { + /** + * The value nonzero determines the "insideness" of a point in the shape by drawing a ray from + * that point to infinity in any direction, and then examining the places where a segment of + * the shape crosses the ray. + * Starting with a count of zero, add one each time a path segment crosses the ray from left to + * right and subtract one each time a path segment crosses the ray from right to left. + * After counting the crossings, if the result is zero then the point is outside the path. + * Otherwise, it is inside. + */ + @Default + Nonzero(Path2D.WIND_NON_ZERO), + /** + * The value evenodd determines the "insideness" of a point in the shape by drawing a ray from + * that point to infinity in any direction and counting the number of path segments from the given + * shape that the ray crosses. If this number is odd, the point is inside; if even, the point is outside. + */ + EvenOdd(Path2D.WIND_EVEN_ODD), + Inherit(Nonzero.awtWindingRule); + + public final int awtWindingRule; + + FillRule(int awtWindingRule) { + this.awtWindingRule = awtWindingRule; + } + + public static @NotNull FillRule parse(@NotNull AttributeNode attributeNode) { + return attributeNode.getEnum("fill-rule", FillRule.Inherit); + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/HasMatchName.java @@ -0,0 +1,29 @@ +/* + * MIT License + * + * Copyright (c) 2021 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes; + +import org.jetbrains.annotations.NotNull; + +public interface HasMatchName { + @NotNull + String matchName(); +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/Inherited.java @@ -0,0 +1,27 @@ +/* + * MIT License + * + * Copyright (c) 2024-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes; + +public enum Inherited { + YES, + NO +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/MarkerOrientation.java @@ -0,0 +1,104 @@ +/* + * MIT License + * + * Copyright (c) 2021-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import com.github.weisj.jsvg.geometry.size.Angle; +import com.github.weisj.jsvg.parser.impl.AttributeParser; + +public abstract class MarkerOrientation { + + private MarkerOrientation() {} + + public enum MarkerType { + START, + MID, + END + } + + public static @NotNull MarkerOrientation parse(@Nullable String value, @NotNull AttributeParser parser) { + if (value == null) return AngleOrientation.DEFAULT; + if ("auto".equals(value)) return AutoOrientation.INSTANCE; + if ("auto-start-reverse".equals(value)) return AutoStartReverseOrientation.INSTANCE; + Angle angle = parser.parseAngle(value, Angle.UNSPECIFIED); + if (angle.isSpecified()) return new AngleOrientation(angle); + return AngleOrientation.DEFAULT; + } + + public abstract float orientationFor(@NotNull MarkerType type, float dxIn, float dyIn, float dxOut, + float dyOut); + + private static final class AutoOrientation extends MarkerOrientation { + private static final @NotNull AutoOrientation INSTANCE = new AutoOrientation(); + + @Override + public float orientationFor(@NotNull MarkerType type, float dxIn, float dyIn, float dxOut, + float dyOut) { + switch (type) { + case START: + return (float) Math.atan2(dyOut, dxOut); + case END: + return (float) Math.atan2(dyIn, dxIn); + case MID: + return (float) Math.atan2((dyIn + dyOut) / 2f, (dxIn + dxOut) / 2f); + default: + throw new IllegalStateException(); + } + } + } + + private static final class AutoStartReverseOrientation extends MarkerOrientation { + private static final @NotNull AutoStartReverseOrientation INSTANCE = new AutoStartReverseOrientation(); + + @Override + public float orientationFor(@NotNull MarkerType type, float dxIn, float dyIn, float dxOut, + float dyOut) { + switch (type) { + case START: + return (float) Math.atan2(-dyOut, -dxOut); + case END: + return (float) Math.atan2(dyIn, dxIn); + case MID: + return (float) Math.atan2((dyIn + dyOut) / 2f, (dxIn + dxOut) / 2f); + default: + throw new IllegalStateException(); + } + } + } + + private static final class AngleOrientation extends MarkerOrientation { + private static final @NotNull AngleOrientation DEFAULT = new AngleOrientation(Angle.ZERO); + private final @NotNull Angle angle; + + private AngleOrientation(@NotNull Angle angle) { + this.angle = angle; + } + + @Override + public float orientationFor(@NotNull MarkerType type, float dxIn, float dyIn, float dxOut, + float dyOut) { + return angle.radians(); + } + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/MarkerUnitType.java @@ -0,0 +1,28 @@ +/* + * MIT License + * + * Copyright (c) 2021 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes; + +public enum MarkerUnitType { + UserSpaceOnUse, + @Default + StrokeWidth +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/MaskType.java @@ -0,0 +1,63 @@ +/* + * MIT License + * + * Copyright (c) 2021-2026 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes; + + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.util.BlittableImage; +import com.github.weisj.jsvg.util.ImageUtil; +import com.github.weisj.jsvg.util.supplier.ImmutableSupplier; + +/** + * Specifies whether the mask is treated as a luminance mask or as an alpha mask. + * + * @see mask-type (MDN) + * @see CSS Masking Level 1 – mask-type + */ +public enum MaskType { + /** + * The luminance values of the mask content determine the mask. + * The effective mask value for a pixel is computed as {@code luminance(color) * alpha}. + * + * @see luminance + */ + @Default + Luminance(() -> ImageUtil::createLuminosityBuffer), + /** + * The alpha values of the mask content determine the mask. + * The effective mask value for a pixel equals its alpha value. + * + * @see alpha + */ + Alpha(() -> ImageUtil::createCompatibleTransparentImage); + + private final @NotNull ImmutableSupplier bufferSurfaceSupplier; + + MaskType(@NotNull ImmutableSupplier bufferSurfaceSupplier) { + this.bufferSurfaceSupplier = bufferSurfaceSupplier; + } + + public @NotNull BlittableImage.BufferSurfaceSupplier bufferSurface() { + return bufferSurfaceSupplier.get(); + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/Overflow.java @@ -0,0 +1,40 @@ +/* + * MIT License + * + * Copyright (c) 2022 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes; + +public enum Overflow { + Auto(false), + @Default + Visible(false), + Hidden(true), + Scroll(true); + + private final boolean establishesClip; + + Overflow(boolean establishesClip) { + this.establishesClip = establishesClip; + } + + public boolean establishesClip() { + return establishesClip; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/PaintOrder.java @@ -0,0 +1,115 @@ +/* + * MIT License + * + * Copyright (c) 2022-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes; + +import java.util.Arrays; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import com.github.weisj.jsvg.parser.impl.AttributeNode; +import com.github.weisj.jsvg.parser.impl.AttributeParser; +import com.github.weisj.jsvg.parser.impl.SeparatorMode; +import com.github.weisj.jsvg.util.AttributeUtil; + +public final class PaintOrder { + + public static final PaintOrder NORMAL = new PaintOrder(Phase.FILL, Phase.STROKE, Phase.MARKERS); + + public enum Phase { + FILL, + STROKE, + MARKERS + } + + private final @NotNull Phase[] phases; + + public PaintOrder(@NotNull Phase... phases) { + this.phases = phases; + } + + public @NotNull Phase[] phases() { + return phases; + } + + public static @Nullable PaintOrder parse(@NotNull AttributeNode attributeNode) { + @Nullable String value = attributeNode.getValue("paint-order"); + @NotNull AttributeParser parser = attributeNode.parser(); + + if (value == null) return null; + if ("inherit".equals(value)) return null; + if ("none".equals(value)) return NORMAL; + if ("normal".equals(value)) return NORMAL; + + String[] rawPhases = parser.parseStringList(value, SeparatorMode.COMMA_AND_WHITESPACE); + Phase[] phases = new Phase[3]; + int length = Math.min(phases.length, rawPhases.length); + int phasesIndex = 0; + int rawPhasesIndex = 0; + while (phasesIndex < length && rawPhasesIndex < length) { + Phase phase = parser.parseEnum(rawPhases[rawPhasesIndex], Phase.class); + if (phase != null && !AttributeUtil.arrayContains(phases, phase)) { + phases[phasesIndex] = phase; + phasesIndex++; + } + rawPhasesIndex++; + } + while (phasesIndex < 3) { + // Fill up with normal order + phases[phasesIndex] = findNextInNormalOrder(phases, phasesIndex); + phasesIndex++; + } + return new PaintOrder(phases); + } + + private static @NotNull Phase findNextInNormalOrder(@NotNull Phase[] phases, int maxIndex) { + for (Phase phase : NORMAL.phases()) { + boolean found = false; + for (int i = 0; i < maxIndex; i++) { + if (phases[i] == phase) { + found = true; + break; + } + } + if (!found) return phase; + } + throw new IllegalStateException(); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + PaintOrder that = (PaintOrder) o; + return Arrays.equals(phases, that.phases); + } + + @Override + public int hashCode() { + return Arrays.hashCode(phases); + } + + @Override + public String toString() { + return "PaintOrder" + Arrays.toString(phases); + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/PresentationAttribute.java @@ -0,0 +1,32 @@ +/* + * MIT License + * + * Copyright (c) 2021 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.SOURCE) +public @interface PresentationAttribute { +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/PreserveAspectRatio.java @@ -0,0 +1,255 @@ +/* + * MIT License + * + * Copyright (c) 2021-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes; + +import java.awt.geom.AffineTransform; +import java.util.Objects; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import com.github.weisj.jsvg.parser.impl.AttributeParser; +import com.github.weisj.jsvg.parser.impl.SeparatorMode; +import com.github.weisj.jsvg.view.FloatSize; +import com.github.weisj.jsvg.view.ViewBox; + + +public final class PreserveAspectRatio { + + private enum AlignType { + Min { + @Override + double align(double size1, double size2) { + return 0; + } + }, + Mid { + @Override + double align(double size1, double size2) { + return (size1 - size2) / 2; + } + }, + Max { + @Override + double align(double size1, double size2) { + return size1 - size2; + } + }; + + abstract double align(double size1, double size2); + } + + public enum Align { + + /** + * Do not force uniform scaling. + * Scale the graphic content of the given element non-uniformly if necessary such that the + * element's bounding box exactly matches the viewport rectangle. + * Note that if [align] is none, then the optional [meetOrSlice] value is ignored. + */ + None(AlignType.Min, AlignType.Min), + /** + * Force uniform scaling. + * Align the [min-x] of the element's viewBox with the smallest X value of the viewport. + * Align the [min-y] of the element's viewBox with the smallest Y value of the viewport. + */ + xMinYMin(AlignType.Min, AlignType.Min), + /** + * Force uniform scaling. + * Align the midpoint X value of the element's viewBox with the midpoint X value of the viewport. + * Align the [min-y] of the element's viewBox with the smallest Y value of the viewport. + */ + xMidYMin(AlignType.Mid, AlignType.Min), + /** + * Force uniform scaling. + * Align the [min-x]+[width] of the element's viewBox with the maximum X value of the viewport. + * Align the [min-y] of the element's viewBox with the smallest Y value of the viewport. + */ + xMaxYMin(AlignType.Max, AlignType.Min), + /** + * Force uniform scaling. + * Align the [min-x] of the element's viewBox with the smallest X value of the viewport. + * Align the midpoint Y value of the element's viewBox with the midpoint Y value of the viewport. + */ + xMinYMid(AlignType.Min, AlignType.Mid), + /** + * Force uniform scaling. + * Align the midpoint X value of the element's viewBox with the midpoint X value of the viewport. + * Align the midpoint Y value of the element's viewBox with the midpoint Y value of the viewport. + */ + @Default + xMidYMid(AlignType.Mid, AlignType.Mid), + /** + * Force uniform scaling. + * Align the [min-x]+[width] of the element's viewBox with the maximum X value of the viewport. + * Align the midpoint Y value of the element's viewBox with the midpoint Y value of the viewport. + */ + xMaxYMid(AlignType.Max, AlignType.Mid), + /** + * Force uniform scaling. + * Align the [min-x] of the element's viewBox with the smallest X value of the viewport. + * Align the [min-y]+[height] of the element's viewBox with the maximum Y value of the viewport. + */ + xMinYMax(AlignType.Min, AlignType.Max), + /** + * Force uniform scaling. + * Align the midpoint X value of the element's viewBox with the midpoint X value of the viewport. + * Align the [min-y]+[height] of the element's viewBox with the maximum Y value of the viewport. + */ + xMidYMax(AlignType.Mid, AlignType.Max), + /** + * Force uniform scaling. + * Align the [min-x]+[width] of the element's viewBox with the maximum X value of the viewport. + * Align the [min-y]+[height] of the element's viewBox with the maximum Y value of the viewport. + */ + xMaxYMax(AlignType.Max, AlignType.Max); + + private final @NotNull AlignType xAlign; + private final @NotNull AlignType yAlign; + + Align(@NotNull AlignType xAlign, @NotNull AlignType yAlign) { + this.xAlign = xAlign; + this.yAlign = yAlign; + } + + @Override + public String toString() { + return name() + "{" + xAlign + ", " + yAlign + "}"; + } + } + + public enum MeetOrSlice { + /** + * Scale the graphic such that: + *

+ * - aspect ratio is preserved + * - the entire viewBox is visible within the viewport + * - the viewBox is scaled up as much as possible, while still meeting the other criteria + *

+ * In this case, if the aspect ratio of the graphic does not match the viewport, + * some viewport will extend beyond the bounds of the viewBox + * (i.e., the area into which the viewBox will draw will be smaller than the viewport). + */ + @Default + Meet, + /** + * Scale the graphic such that: + *

+ * - aspect ratio is preserved + * - the entire viewport is covered by the viewBox + * - the viewBox is scaled down as much as possible, while still meeting the other criteria + *

+ * In this case, if the aspect ratio of the viewBox does not match the viewport, some + * viewBox will extend beyond the bounds of the viewport + * (i.e., the area into which the viewBox will draw is larger than the viewport). + */ + Slice + } + + public final @NotNull Align align; + public final @NotNull MeetOrSlice meetOrSlice; + + private PreserveAspectRatio(@NotNull Align align, @NotNull MeetOrSlice meetOrSlice) { + this.align = align; + this.meetOrSlice = meetOrSlice; + } + + public static @NotNull PreserveAspectRatio none() { + return new PreserveAspectRatio(Align.None, MeetOrSlice.Meet); + } + + public static @NotNull PreserveAspectRatio forDisplay() { + return new PreserveAspectRatio(Align.xMidYMid, MeetOrSlice.Meet); + } + + public static @NotNull PreserveAspectRatio parse(@Nullable String preserveAspectRation, + @NotNull AttributeParser parser) { + return parse(preserveAspectRation, null, parser); + } + + public static @NotNull PreserveAspectRatio parse(@Nullable String preserveAspectRation, + @Nullable PreserveAspectRatio fallback, @NotNull AttributeParser parser) { + Align align = Align.xMidYMid; + MeetOrSlice meetOrSlice = MeetOrSlice.Meet; + if (preserveAspectRation == null) { + return fallback != null ? fallback : new PreserveAspectRatio(align, meetOrSlice); + } + String[] components = + parser.parseStringList(preserveAspectRation, SeparatorMode.COMMA_AND_WHITESPACE); + if (components.length < 1 || components.length > 2) + throw new IllegalArgumentException("Too many arguments specified: " + preserveAspectRation); + align = parser.parseEnum(components[0], align); + if (components.length > 1) + meetOrSlice = parser.parseEnum(components[1], meetOrSlice); + return new PreserveAspectRatio(align, meetOrSlice); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof PreserveAspectRatio)) return false; + PreserveAspectRatio that = (PreserveAspectRatio) o; + return align == that.align && meetOrSlice == that.meetOrSlice; + } + + @Override + public int hashCode() { + return Objects.hash(align, meetOrSlice); + } + + // https://www.w3.org/TR/SVG2/coords.html#ComputingAViewportsTransform + public @NotNull AffineTransform computeViewportTransform(@NotNull FloatSize size, @NotNull ViewBox viewBox) { + AffineTransform viewTransform = new AffineTransform(); + if (align == Align.None) { + viewTransform.scale(size.width / viewBox.width, size.height / viewBox.height); + } else { + double xScale = size.width / viewBox.width; + double yScale = size.height / viewBox.height; + + switch (meetOrSlice) { + case Meet: + xScale = yScale = Math.min(xScale, yScale); + break; + case Slice: + xScale = yScale = Math.max(xScale, yScale); + break; + default: + throw new IllegalStateException(); + } + + viewTransform.translate( + align.xAlign.align(size.width, viewBox.width * xScale), + align.yAlign.align(size.height, viewBox.height * yScale)); + viewTransform.scale(xScale, yScale); + } + viewTransform.translate(-viewBox.x, -viewBox.y); + return viewTransform; + } + + @Override + public String toString() { + return "PreserveAspectRatio{" + + "align=" + align + + ", meetOrSlice=" + meetOrSlice + + '}'; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/SpreadMethod.java @@ -0,0 +1,42 @@ +/* + * MIT License + * + * Copyright (c) 2021-2023 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes; + +import java.awt.*; + +import org.jetbrains.annotations.NotNull; + +public enum SpreadMethod { + Pad(MultipleGradientPaint.CycleMethod.NO_CYCLE), + Reflect(MultipleGradientPaint.CycleMethod.REFLECT), + Repeat(MultipleGradientPaint.CycleMethod.REPEAT); + + private final MultipleGradientPaint.CycleMethod cycleMethod; + + SpreadMethod(MultipleGradientPaint.CycleMethod cycleMethod) { + this.cycleMethod = cycleMethod; + } + + public @NotNull MultipleGradientPaint.CycleMethod cycleMethod() { + return cycleMethod; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/SuffixUnit.java @@ -0,0 +1,36 @@ +/* + * MIT License + * + * Copyright (c) 2024 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes; + +import org.jetbrains.annotations.NotNull; + +public interface SuffixUnit { + + @NotNull + String suffix(); + + @NotNull + SuffixUnit @NotNull [] units(); + + @NotNull + V valueOf(float value); +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/UnitType.java @@ -0,0 +1,73 @@ +/* + * MIT License + * + * Copyright (c) 2021-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes; + +import java.awt.geom.AffineTransform; +import java.awt.geom.Rectangle2D; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.geometry.size.Length; +import com.github.weisj.jsvg.renderer.MeasureContext; + +public enum UnitType { + UserSpaceOnUse, + @Default + ObjectBoundingBox; + + public @NotNull MeasureContext deriveMeasure(@NotNull MeasureContext measure) { + return deriveMeasure(measure, 1, 1); + } + + public @NotNull MeasureContext deriveMeasure(@NotNull MeasureContext measure, double objectWidth, + double objectHeight) { + if (this == ObjectBoundingBox) { + return measure.derive((float) objectWidth, (float) objectHeight); + } else { + return measure; + } + } + + public @NotNull AffineTransform viewTransform(@NotNull Rectangle2D bounds) { + if (this == ObjectBoundingBox) { + AffineTransform at = AffineTransform.getTranslateInstance(bounds.getX(), bounds.getY()); + at.scale(bounds.getWidth(), bounds.getHeight()); + return at; + } else { + return new AffineTransform(); + } + } + + public @NotNull Rectangle2D.Double computeViewBounds( + @NotNull MeasureContext measure, @NotNull Rectangle2D elementBounds, + @NotNull Length x, @NotNull Length y, @NotNull Length width, @NotNull Length height) { + MeasureContext patternMeasure = deriveMeasure(measure, elementBounds.getWidth(), elementBounds.getHeight()); + Rectangle2D.Double viewBounds = new Rectangle2D.Double( + x.resolve(patternMeasure), y.resolve(patternMeasure), + width.resolve(patternMeasure), height.resolve(patternMeasure)); + if (this == ObjectBoundingBox) { + viewBounds.x += elementBounds.getX(); + viewBounds.y += elementBounds.getY(); + } + return viewBounds; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/VectorEffect.java @@ -0,0 +1,180 @@ +/* + * MIT License + * + * Copyright (c) 2022-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes; + +import java.awt.*; +import java.awt.geom.AffineTransform; +import java.util.EnumSet; +import java.util.Set; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import com.github.weisj.jsvg.geometry.util.GeometryUtil; +import com.github.weisj.jsvg.parser.impl.AttributeNode; +import com.github.weisj.jsvg.renderer.RenderContext; +import com.github.weisj.jsvg.renderer.output.Output; +import com.github.weisj.jsvg.util.ShapeUtil; + + +public enum VectorEffect implements HasMatchName { + None(0), + NonScalingStroke("non-scaling-stroke", 0), + NonScalingSize("non-scaling-size", Flags.NON_SCALING_SIZE), + NonRotation("non-rotation", Flags.NON_ROTATING), + FixedPosition("fixed-position", Flags.FIXED_POSITION); + + + private final @NotNull String matchName; + private final int flag; + + VectorEffect(int flag) { + this.matchName = name(); + this.flag = flag; + } + + VectorEffect(@NotNull String matchName, int flag) { + this.matchName = matchName; + this.flag = flag; + } + + public static @NotNull Set parse(@NotNull AttributeNode attributeNode) { + @NotNull String[] vectorEffectsRaw = attributeNode.getStringList("vector-effect"); + EnumSet vectorEffects = EnumSet.noneOf(VectorEffect.class); + for (String effect : vectorEffectsRaw) { + vectorEffects.add(attributeNode.parser().parseEnum(effect, VectorEffect.None)); + } + return vectorEffects; + } + + @Override + public @NotNull String matchName() { + return matchName; + } + + private static int flags(@NotNull Set effects) { + int flag = 0; + for (VectorEffect effect : effects) { + flag |= effect.flag; + } + return flag; + } + + public static void applyEffects(@NotNull Set effects, @NotNull Output output, + @NotNull RenderContext context, @Nullable AffineTransform elementTransform) { + int flags = flags(effects); + if (flags == 0) return; + + AffineTransform shapeTransform = new AffineTransform(context.userSpaceTransform()); + + double x0 = elementTransform != null ? elementTransform.getTranslateX() : 0; + double y0 = elementTransform != null ? elementTransform.getTranslateY() : 0; + + updateTransformForFlags(flags, shapeTransform, x0, y0); + + output.setTransform(context.rootTransform()); + output.applyTransform(shapeTransform); + } + + // https://svgwg.org/svg2-draft/painting.html#PaintingVectorEffects + public static @NotNull Shape applyNonScalingStroke(@NotNull Output output, @NotNull RenderContext context, + @NotNull Stroke stroke, @NotNull Shape shape) { + // For the stroke not to be scaled we have to pre-multiply the shape by the transform and then paint + // in the non-transformed coordinate system. + Shape strokedShape = ShapeUtil.transformShape(shape, context.userSpaceTransform()); + strokedShape = stroke.createStrokedShape(strokedShape); + return ShapeUtil.transformShape(strokedShape, GeometryUtil.createInverse(context.userSpaceTransform())); + } + + private static void updateTransformForFlags(int flags, @NotNull AffineTransform transform, double x0, double y0) { + switch (flags) { + case Flags.NON_SCALING_SIZE: { + double detRoot = Math.sqrt(Math.abs(transform.getDeterminant())); + if (detRoot == 0) return; + double detRootInv = 1 / detRoot; + transform.setTransform( + transform.getScaleX() * detRootInv, transform.getShearY() * detRootInv, + transform.getShearX() * detRootInv, transform.getScaleY() * detRootInv, + transform.getTranslateX(), + transform.getTranslateY()); + break; + } + case Flags.NON_ROTATING: { + double detRoot = Math.sqrt(Math.abs(transform.getDeterminant())); + transform.setTransform( + detRoot, 0, 0, detRoot, + transform.getTranslateX(), + transform.getTranslateY()); + break; + } + case Flags.NON_SCALING_SIZE | Flags.NON_ROTATING: { + transform.setTransform( + 1, 0, 0, 1, + transform.getTranslateX(), + transform.getTranslateY()); + break; + } + case Flags.FIXED_POSITION: { + transform.setTransform( + transform.getScaleX(), transform.getShearY(), + transform.getShearX(), transform.getScaleY(), + x0, + y0); + break; + } + case Flags.FIXED_POSITION | Flags.NON_SCALING_SIZE: { + double detRoot = Math.sqrt(Math.abs(transform.getDeterminant())); + if (detRoot == 0) return; + double detRootInv = 1 / detRoot; + transform.setTransform( + transform.getScaleX() * detRootInv, transform.getShearY() * detRootInv, + transform.getShearX() * detRootInv, transform.getScaleY() * detRootInv, + x0, + y0); + break; + } + case Flags.FIXED_POSITION | Flags.NON_ROTATING: { + double detRoot = Math.sqrt(Math.abs(transform.getDeterminant())); + transform.setTransform( + detRoot, 0, 0, detRoot, + x0, + y0); + break; + } + case Flags.FIXED_POSITION | Flags.NON_ROTATING | Flags.NON_SCALING_SIZE: { + transform.setTransform( + 1, 0, 0, 1, + x0, + y0); + break; + } + default: + break; + } + } + + private static final class Flags { + private static final int NON_SCALING_SIZE = 1; + private static final int NON_ROTATING = 1 << 1; + private static final int FIXED_POSITION = 1 << 2; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/filter/BlendMode.java @@ -0,0 +1,131 @@ +/* + * MIT License + * + * Copyright (c) 2022 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.filter; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.attributes.HasMatchName; + +public enum BlendMode implements HasMatchName { + /** + * The final color is the top color, regardless of what the bottom color is. + * The effect is like two opaque pieces of paper overlapping. + */ + Normal, + /** + * The final color is the result of multiplying the top and bottom colors. + * A black layer leads to a black final layer, and a white layer leads to no change. + * The effect is like two images printed on transparent film overlapping. + */ + Multiply, + /** + * The final color is the result of inverting the colors, multiplying them, and inverting that value. + * A black layer leads to no change, and a white layer leads to a white final layer. + * The effect is like two images shone onto a projection screen. + */ + Screen, + /** + * The final color is the result of multiply if the bottom color is darker, + * or screen if the bottom color is lighter. + * This blend mode is equivalent to hard-light but with the layers swapped. + */ + Overlay, + /** + * The final color is composed of the darkest values of each color channel. + */ + Darken, + /** + * The final color is composed of the lightest values of each color channel. + */ + Lighten, + /** + * The final color is the result of dividing the bottom color by the inverse of the top color. + * A black foreground leads to no change. A foreground with the inverse color of the backdrop + * leads to a fully lit color. This blend mode is similar to screen, but the foreground need only be + * as light as the inverse of the backdrop to create a fully lit color. + */ + ColorDodge("color-dodge"), + /** + * The final color is the result of inverting the bottom color, dividing the value by the top color, + * and inverting that value. A white foreground leads to no change. + * A foreground with the inverse color of the backdrop leads to a black final image. + * This blend mode is similar to multiply, but the foreground need only be as dark as the inverse of the backdrop + * to make the final image black. + */ + ColorBurn("color-burn"), + /** + * The final color is the result of multiply if the top color is darker, or screen if the top color is lighter. + * This blend mode is equivalent to overlay but with the layers swapped. + * The effect is similar to shining a harsh spotlight on the backdrop. + */ + HardLight("hard-light"), + /** + * The final color is similar to hard-light, but softer. This blend mode behaves similar to hard-light. + * The effect is similar to shining a diffused spotlight on the backdrop. + */ + SoftLight("soft-light"), + /** + * The final color is the result of subtracting the darker of the two colors from the lighter one. + * A black layer has no effect, while a white layer inverts the other layer's color. + */ + Difference, + /** + * The final color is similar to difference, but with less contrast. As with difference, a black layer has no + * effect, while a white layer inverts the other layer's color. + */ + Exclusion, + /** + * The final color has the hue of the top color, while using the saturation and luminosity of the bottom color. + */ + Hue, + /** + * The final color has the saturation of the top color, while using the hue and luminosity of the bottom color. + * A pure gray backdrop, having no saturation, will have no effect. + */ + Saturation, + /** + * The final color has the hue and saturation of the top color, while using the luminosity of the bottom color. + * The effect preserves gray levels and can be used to colorize the foreground. + */ + Color, + /** + * The final color has the luminosity of the top color, while using the hue and saturation of the bottom color. + * This blend mode is equivalent to color, but with the layers swapped. + */ + Luminosity; + + private final @NotNull String matchName; + + BlendMode(@NotNull String matchName) { + this.matchName = matchName; + } + + BlendMode() { + this.matchName = name(); + } + + + @Override + public @NotNull String matchName() { + return matchName; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/filter/ColorChannel.java @@ -0,0 +1,39 @@ +/* + * MIT License + * + * Copyright (c) 2021 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.filter; + +public enum ColorChannel { + R(2), + G(1), + B(0), + A(3); + + private final int index; + + ColorChannel(int index) { + this.index = index; + } + + public int value(int pixelData) { + return (pixelData >> (index * 8)) & 0xFF; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/filter/CompositeMode.java @@ -0,0 +1,76 @@ +/* + * MIT License + * + * Copyright (c) 2023 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.filter; + +import com.github.weisj.jsvg.attributes.Default; + +public enum CompositeMode { + /** + * The source graphic defined by the in attribute (the MDN logo) is placed over + * the destination graphic defined by the in2 attribute (the circle). + * This is the default operation, which will be used if no operation or + * an unsupported operation is specified. + */ + @Default + Over, + /** + * The parts of the source graphic defined by the in attribute that overlap + * the destination graphic defined in the in2 attribute, replace the destination graphic. + */ + In, + /** + * The parts of the source graphic defined by the in attribute that fall outside the destination + * graphic defined in the in2 attribute, are displayed. + */ + Out, + /** + * The parts of the source graphic defined in the in attribute, which overlap the destination graphic defined + * in the in2 attribute, replace the destination graphic. + * The parts of the destination graphic that do not overlap with the source graphic stay untouched. + */ + Atop, + /** + * The non-overlapping regions of the source graphic defined in the in attribute and + * the destination graphic defined in the in2 attribute are combined. + */ + Xor, + /** + * The sum of the source graphic defined in the in attribute and the + * destination graphic defined in the in2 attribute is displayed. + */ + Lighter, + /** + * The arithmetic operation is useful for combining the output from the + * feDiffuseLighting and feSpecularLighting filters with texture data. + * If the arithmetic operation is chosen, each result pixel is computed using the following formula: + *

+ * result = k1*i1*i2 + k2*i1 + k3*i2 + k4 + *

+ * where: + *

    + *
  • i1 and i2 indicate the corresponding pixel channel values of the input image, + * which map to in and in2 respectively
  • + *
  • k1, k2, k3, and k4 indicate the values of the attributes with the same name.
  • + *
+ */ + Arithmetic +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/filter/DefaultFilterChannel.java @@ -0,0 +1,67 @@ +/* + * MIT License + * + * Copyright (c) 2021-2023 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.filter; + +import org.jetbrains.annotations.NotNull; + +public enum DefaultFilterChannel implements FilterChannelKey { + /** + * This keyword represents the graphics elements that were the original input into the element. + */ + SourceGraphic, + /** + * This keyword represents the graphics elements that were the original input into the element. + * SourceAlpha has all the same rules as SourceGraphic except that only the alpha channel is used. + */ + SourceAlpha, + /** + * This keyword represents an image snapshot of the SVG document under the filter region at the time that the + * element was invoked. + */ + BackgroundImage, + /** + * Same as BackgroundImage except only the alpha channel is used. + */ + BackgroundAlpha, + /** + * This keyword represents the value of the fill property on the target element for the filter effect. + * In many cases, the FillPaint is opaque everywhere, but that might not be the case if a shape is painted with a + * gradient or pattern which itself includes transparent or semi-transparent parts. + */ + FillPaint, + /** + * This keyword represents the value of the stroke property on the target element for the filter effect. + * In many cases, the StrokePaint is opaque everywhere, but that might not be the case if a shape is painted with a + * gradient or pattern which itself includes transparent or semi-transparent parts. + */ + StrokePaint, + /** + * Uses the result of the preceding filter or SourceGraphic if this is the first filter. + */ + LastResult; + + @Override + public @NotNull Object key() { + if (this == LastResult) return this; + return toString(); + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/filter/EdgeMode.java @@ -0,0 +1,200 @@ +/* + * MIT License + * + * Copyright (c) 2021-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.filter; + +import java.awt.*; +import java.awt.image.*; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import com.github.weisj.jsvg.nodes.filter.FilterContext; +import com.github.weisj.jsvg.renderer.RenderContext; +import com.github.weisj.jsvg.renderer.output.impl.GraphicsUtil; +import com.github.weisj.jsvg.util.ImageUtil; + +public enum EdgeMode { + Duplicate { + @Override + public ImageProducer convolve(@NotNull RenderContext context, @NotNull FilterContext filterContext, + @NotNull ImageProducer producer, @NotNull ConvolveOperation convolveOperation) { + return convolveDuplicate(context, filterContext, producer, convolveOperation); + } + }, + Wrap { + @Override + public ImageProducer convolve(@NotNull RenderContext context, @NotNull FilterContext filterContext, + @NotNull ImageProducer producer, @NotNull ConvolveOperation convolveOperation) { + return convolveWrap(context, filterContext, producer, convolveOperation); + } + }, + None { + @Override + public ImageProducer convolve(@NotNull RenderContext context, @NotNull FilterContext filterContext, + @NotNull ImageProducer producer, @NotNull ConvolveOperation convolveOperation) { + return applyConvolutions(filterContext.renderingHints(), + ImageUtil.copy(context, producer, ImageUtil.Premultiplied.Yes), + convolveOperation, ConvolveOp.EDGE_ZERO_FILL); + } + }; + + public abstract ImageProducer convolve(@NotNull RenderContext context, @NotNull FilterContext filterContext, + @NotNull ImageProducer producer, @NotNull ConvolveOperation convolveOperation); + + public interface ConvolveOperation { + + @NotNull + Dimension maximumKernelSize(); + + @NotNull + ImageProducer convolve(@NotNull BufferedImage image, @Nullable RenderingHints hints, int awtEdgeMode); + } + + private static final class EdgeModeImage { + private final @NotNull BufferedImage img; + private final int xOff; + private final int yOff; + private final int width; + private final int height; + + private EdgeModeImage(@NotNull BufferedImage img, int xOff, int yOff, int width, int height) { + this.img = img; + this.xOff = xOff; + this.yOff = yOff; + this.width = width; + this.height = height; + } + } + + private static EdgeModeImage prepareEdgeModeImage(@NotNull RenderContext context, + @NotNull ImageProducer producer, @NotNull ConvolveOperation convolveOperation) { + Image img = context.platformSupport().createImage(producer); + int width = img.getWidth(null); + int height = img.getHeight(null); + + Dimension kernelSize = convolveOperation.maximumKernelSize(); + int xSize = kernelSize.width; + int ySize = kernelSize.height; + + BufferedImage bufferedImage = ImageUtil.createCompatibleTransparentImage(width + xSize, height + ySize, + ImageUtil.Premultiplied.Yes); + Graphics2D g = GraphicsUtil.createGraphics(bufferedImage); + + int xOff = xSize / 2; + int yOff = ySize / 2; + + g.translate(xOff, yOff); + g.drawImage(img, null, null); + g.dispose(); + + return new EdgeModeImage(bufferedImage, xOff, yOff, width, height); + } + + private static @NotNull ImageProducer convolveDuplicate(@NotNull RenderContext context, + @NotNull FilterContext filterContext, @NotNull ImageProducer producer, + @NotNull ConvolveOperation convolveOperation) { + EdgeModeImage edgeModeImage = prepareEdgeModeImage(context, producer, convolveOperation); + int xOff = edgeModeImage.xOff; + int yOff = edgeModeImage.yOff; + int width = edgeModeImage.width; + int height = edgeModeImage.height; + + Graphics2D g = GraphicsUtil.createGraphics(edgeModeImage.img); + + BufferedImage top = edgeModeImage.img.getSubimage(xOff, yOff, width, 1); + BufferedImage left = edgeModeImage.img.getSubimage(xOff, yOff, 1, height); + BufferedImage right = edgeModeImage.img.getSubimage(xOff + width - 1, yOff, 1, height); + BufferedImage bottom = edgeModeImage.img.getSubimage(xOff, yOff + height - 1, width, 1); + + g.drawImage(top, xOff, 0, width, yOff, null); + g.drawImage(bottom, xOff, yOff + height, width, yOff, null); + g.drawImage(left, 0, yOff, xOff, height, null); + g.drawImage(right, xOff + height, yOff, xOff, height, null); + + Color topLeft = new Color(top.getRGB(0, 0), true); + Color topRight = new Color(top.getRGB(top.getWidth() - 1, 0), true); + Color bottomLeft = new Color(bottom.getRGB(0, 0), true); + Color bottomRight = new Color(bottom.getRGB(bottom.getWidth() - 1, 0), true); + + g.setColor(topLeft); + g.fillRect(0, 0, xOff, yOff); + + g.setColor(topRight); + g.fillRect(xOff + width, 0, xOff, yOff); + + g.setColor(bottomLeft); + g.fillRect(0, yOff + height, xOff, yOff); + + g.setColor(bottomRight); + g.fillRect(xOff + width, yOff + height, xOff, yOff); + + g.dispose(); + + ImageProducer output = + applyConvolutions(filterContext.renderingHints(), edgeModeImage.img, convolveOperation, + ConvolveOp.EDGE_NO_OP); + CropImageFilter cropImageFilter = new CropImageFilter(xOff, yOff, width, height); + return new FilteredImageSource(output, cropImageFilter); + } + + private static ImageProducer convolveWrap(@NotNull RenderContext context, @NotNull FilterContext filterContext, + @NotNull ImageProducer producer, @NotNull ConvolveOperation convolveOperation) { + EdgeModeImage edgeModeImage = prepareEdgeModeImage(context, producer, convolveOperation); + int xOff = edgeModeImage.xOff; + int yOff = edgeModeImage.yOff; + int width = edgeModeImage.width; + int height = edgeModeImage.height; + + Graphics2D g = GraphicsUtil.createGraphics(edgeModeImage.img); + + BufferedImage top = edgeModeImage.img.getSubimage(xOff, yOff, width, yOff); + BufferedImage left = edgeModeImage.img.getSubimage(xOff, yOff, xOff, height); + BufferedImage right = edgeModeImage.img.getSubimage(width - 1, yOff, xOff, height); + BufferedImage bottom = edgeModeImage.img.getSubimage(xOff, height - 1, width, yOff); + + BufferedImage topLeft = edgeModeImage.img.getSubimage(xOff, yOff, xOff, yOff); + BufferedImage topRight = edgeModeImage.img.getSubimage(width - 1, yOff, xOff, yOff); + BufferedImage bottomLeft = edgeModeImage.img.getSubimage(xOff, height - 1, width, yOff); + BufferedImage bottomRight = edgeModeImage.img.getSubimage(width - 1, height - 1, xOff, yOff); + + g.drawImage(bottom, xOff, 0, null); + g.drawImage(top, xOff, yOff + height, null); + g.drawImage(right, 0, yOff, null); + g.drawImage(left, xOff + width, yOff, null); + + g.drawImage(bottomRight, 0, 0, null); + g.drawImage(bottomLeft, xOff + width, 0, null); + g.drawImage(topRight, 0, yOff + height, null); + g.drawImage(topLeft, xOff + width, yOff + height, null); + + ImageProducer output = applyConvolutions(filterContext.renderingHints(), edgeModeImage.img, convolveOperation, + ConvolveOp.EDGE_NO_OP); + CropImageFilter cropImageFilter = new CropImageFilter(xOff, yOff, width, height); + return new FilteredImageSource(output, cropImageFilter); + } + + private static ImageProducer applyConvolutions(@Nullable RenderingHints hints, @NotNull BufferedImage image, + @NotNull ConvolveOperation convolveOperation, int awtEdgeMode) { + return convolveOperation.convolve(image, hints, awtEdgeMode); + } + +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/filter/FilterChannelKey.java @@ -0,0 +1,50 @@ +/* + * MIT License + * + * Copyright (c) 2023 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.filter; + +import org.jetbrains.annotations.NotNull; + +public interface FilterChannelKey { + + @NotNull + Object key(); + + class StringKey implements FilterChannelKey { + private final @NotNull String key; + + public StringKey(@NotNull String key) { + this.key = key; + } + + @Override + public @NotNull Object key() { + return key; + } + + @Override + public String toString() { + return "StringKey{" + + "key='" + key + '\'' + + '}'; + } + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/filter/LayoutBounds.java @@ -0,0 +1,152 @@ +/* + * MIT License + * + * Copyright (c) 2023-2024 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.filter; + +import java.awt.geom.Rectangle2D; +import java.util.function.BiFunction; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.geometry.size.FloatInsets; +import com.github.weisj.jsvg.geometry.util.GeometryUtil; +import com.github.weisj.jsvg.nodes.filter.FilterLayoutContext; + +public final class LayoutBounds { + + public static final class Data { + private final @NotNull Rectangle2D bounds; + private final @NotNull FloatInsets clipBoundsEscapeInsets; + + private Data(@NotNull Rectangle2D bounds, @NotNull FloatInsets clipBoundsEscapeInsets) { + this.bounds = bounds; + this.clipBoundsEscapeInsets = clipBoundsEscapeInsets; + } + + public @NotNull FloatInsets clipBoundsEscapeInsets() { + return clipBoundsEscapeInsets; + } + + public @NotNull Rectangle2D bounds() { + return bounds; + } + + @Override + public String toString() { + return "Data{" + + "bounds=" + GeometryUtil.compactRepresentation(bounds) + + ", clipBoundsEscapeInsets=" + clipBoundsEscapeInsets + + '}'; + } + } + + public static class ComputeFlags { + + public static final @NotNull ComputeFlags INITIAL = new ComputeFlags(false); + public final boolean operatesOnWholeFilterRegion; + + public ComputeFlags(boolean operatesOnWholeFilterRegion) { + this.operatesOnWholeFilterRegion = operatesOnWholeFilterRegion; + } + + public @NotNull ComputeFlags or(@NotNull ComputeFlags other) { + return new ComputeFlags(operatesOnWholeFilterRegion || other.operatesOnWholeFilterRegion); + } + } + + private final @NotNull Data data; + private final @NotNull BiFunction<@NotNull Data, ComputeFlags, @NotNull Data> transformer; + private final ComputeFlags additionalFlags; + + public LayoutBounds(@NotNull Rectangle2D bounds, @NotNull FloatInsets clipBoundsEscapeInsets) { + data = new Data(bounds, clipBoundsEscapeInsets); + transformer = (d, f) -> d; + additionalFlags = new ComputeFlags(false); + } + + private LayoutBounds(@NotNull Data data, + @NotNull BiFunction<@NotNull Data, ComputeFlags, @NotNull Data> transformer, + @NotNull ComputeFlags flags) { + this.data = data; + this.transformer = transformer; + this.additionalFlags = flags; + } + + public @NotNull LayoutBounds transform( + @NotNull BiFunction<@NotNull Data, ComputeFlags, @NotNull Data> newTransformer) { + return new LayoutBounds(data, (data, flags) -> { + Data newData = transformer.apply(data, flags); + return newTransformer.apply(newData, flags); + }, additionalFlags); + } + + public @NotNull LayoutBounds withFlags(@NotNull ComputeFlags flags) { + return new LayoutBounds(data, transformer, additionalFlags.or(flags)); + } + + public @NotNull Data resolve(@NotNull ComputeFlags flags) { + return transformer.apply(data, flags.or(additionalFlags)); + } + + public @NotNull LayoutBounds union(@NotNull LayoutBounds other) { + return transform((data, flags) -> { + Data otherData = other.resolve(flags); + return new Data( + data.bounds.createUnion(otherData.bounds), + GeometryUtil.max(data.clipBoundsEscapeInsets, otherData.clipBoundsEscapeInsets)); + }); + } + + public @NotNull LayoutBounds grow(float horizontal, float vertical, @NotNull FilterLayoutContext context) { + return transform((data, flags) -> { + FloatInsets insets = data.clipBoundsEscapeInsets; + Rectangle2D clipBounds = context.clipBounds(); + FloatInsets growInsets = new FloatInsets(vertical, horizontal, vertical, horizontal); + Rectangle2D newBounds = GeometryUtil.grow(data.bounds, growInsets); + FloatInsets ins = GeometryUtil.min(GeometryUtil.overhangInsets(clipBounds, newBounds), growInsets); + return new Data(newBounds, GeometryUtil.max(insets, ins)); + }); + } + + public @NotNull LayoutBounds translate(float dx, float dy, @NotNull FilterLayoutContext context) { + return transform((data, flags) -> { + FloatInsets insets = data.clipBoundsEscapeInsets; + FloatInsets offsetInsets = new FloatInsets( + Math.max(dy, 0), + Math.max(dx, 0), + Math.max(-dy, 0), + Math.max(-dx, 0)); + Rectangle2D newBounds = GeometryUtil.grow(data.bounds, offsetInsets); + Rectangle2D clipBounds = context.clipBounds(); + // The new layout rect is the union of the original rect and the shifted rect. + FloatInsets ins = GeometryUtil.max(GeometryUtil.overhangInsets(clipBounds, data.bounds), offsetInsets); + return new Data(newBounds, GeometryUtil.max(insets, ins)); + }); + } + + @Override + public String toString() { + return "LayoutBounds{" + + "data=" + data + + ", transformer=" + transformer + + '}'; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/filter/TransferFunctionType.java @@ -0,0 +1,30 @@ +/* + * MIT License + * + * Copyright (c) 2024 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.filter; + +public enum TransferFunctionType { + Identity, + Table, + Discrete, + Linear, + Gamma +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/filter/package-info.java @@ -0,0 +1,3 @@ +@org.osgi.annotation.bundle.Export +@aQute.bnd.annotation.jpms.ExportTo("com.github.weisj.jsvg.javafx") +package com.github.weisj.jsvg.attributes.filter; --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/font/AWTSVGFont.java @@ -0,0 +1,162 @@ +/* + * MIT License + * + * Copyright (c) 2021-2024 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.font; + +import java.awt.*; +import java.awt.font.FontRenderContext; +import java.awt.font.GlyphMetrics; +import java.awt.font.GlyphVector; +import java.awt.font.LineMetrics; +import java.util.HashMap; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import com.github.weisj.jsvg.geometry.size.Length; +import com.github.weisj.jsvg.nodes.text.EmojiGlyph; +import com.github.weisj.jsvg.nodes.text.Glyph; + +public final class AWTSVGFont implements SVGFont { + + private final @NotNull Font font; + private final FontRenderContext frc = new FontRenderContext(null, true, true); + private final HashMap glyphCache; + + private @Nullable LineMetrics lineMetrics; + private float[] baselineOffsets; + private float exHeight = Length.UNSPECIFIED_RAW; + private float mathBaseline = Length.UNSPECIFIED_RAW; + + public AWTSVGFont(@NotNull Font font) { + this.font = font; + this.glyphCache = new HashMap<>(); + } + + public @NotNull Font font() { + return font; + } + + @Override + public @NotNull Glyph codepointGlyph(@NotNull String codepoint) { + Glyph glyph = glyphCache.get(codepoint); + if (glyph != null) return glyph; + glyph = createGlyph(codepoint.toCharArray()); + glyphCache.put(codepoint, glyph); + return glyph; + } + + @Override + public @NotNull String family() { + return font.getFamily(); + } + + @Override + public int size() { + return font.getSize(); + } + + private @NotNull LineMetrics lineMetrics() { + if (lineMetrics == null) { + lineMetrics = font.getLineMetrics("Ax-", 0, 1, frc); + } + return lineMetrics; + } + + @Override + public float effectiveExHeight() { + if (Length.isUnspecified(exHeight)) { + exHeight = (float) codepointGlyph("x").glyphOutline().getBounds2D().getHeight(); + } + return exHeight; + } + + @Override + public float effectiveEmHeight() { + return font.getSize2D(); + } + + @Override + public float mathematicalBaseline() { + if (Length.isUnspecified(mathBaseline)) { + mathBaseline = -effectiveExHeight() / 2; + } + return mathBaseline; + } + + private float[] baselineOffsets() { + if (baselineOffsets == null) baselineOffsets = lineMetrics().getBaselineOffsets(); + return baselineOffsets; + } + + @Override + public float hangingBaseline() { + return baselineOffsets()[Font.HANGING_BASELINE]; + } + + @Override + public float romanBaseline() { + return baselineOffsets()[Font.ROMAN_BASELINE]; + } + + @Override + public float centerBaseline() { + return baselineOffsets()[Font.CENTER_BASELINE]; + } + + @Override + public float middleBaseline() { + return (romanBaseline() - effectiveExHeight()) / 2; + } + + @Override + public float textUnderBaseline() { + return lineMetrics().getUnderlineOffset(); + } + + @Override + public float textOverBaseline() { + return textUnderBaseline() - effectiveEmHeight(); + } + + @NotNull + private Glyph createGlyph(char @NotNull [] codepoint) { + GlyphVector glyphVector = font.createGlyphVector(frc, codepoint); + GlyphMetrics gm = glyphVector.getGlyphMetrics(0); + float advance = gm.getAdvanceX(); + + if (isPossibleEmoji(codepoint)) { + return new EmojiGlyph(String.valueOf(codepoint), advance); + } + + Shape shape = glyphVector.getOutline(0, 0); + return new Glyph(shape, advance, gm.getBounds2D().isEmpty()); + } + + private static boolean isPossibleEmoji(char @NotNull [] codepoint) { + for (char c : codepoint) { + if (Character.isHighSurrogate(c) || Character.isLowSurrogate(c)) { + return true; + } + } + return false; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/font/AttributeFontSpec.java @@ -0,0 +1,83 @@ +/* + * MIT License + * + * Copyright (c) 2021-2024 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.font; + +import java.util.Arrays; +import java.util.Objects; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import com.github.weisj.jsvg.geometry.size.Length; +import com.github.weisj.jsvg.geometry.size.Percentage; +import com.github.weisj.jsvg.nodes.prototype.Mutator; + +public final class AttributeFontSpec extends FontSpec implements Mutator { + private final @Nullable FontSize size; + private final @Nullable FontWeight weight; + + AttributeFontSpec(@NotNull String[] families, @Nullable FontStyle style, @Nullable Length sizeAdjust, + @NotNull Percentage stretch, @Nullable FontSize size, @Nullable FontWeight weight) { + super(families, style, sizeAdjust, stretch); + this.size = size; + this.weight = weight; + } + + public @Nullable FontWeight weight() { + return weight; + } + + public @Nullable FontSize size() { + return size; + } + + @Override + public @NotNull MeasurableFontSpec mutate(@NotNull MeasurableFontSpec element) { + return element.derive(this); + } + + @Override + public String toString() { + return "AttributeFontSpec{" + + "families=" + Arrays.toString(families) + + ", style=" + style + + ", weight=" + weight + + ", size=" + size + + ", sizeAdjust=" + sizeAdjust + + ", stretch=" + stretch + + '}'; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof AttributeFontSpec)) return false; + if (!super.equals(o)) return false; + AttributeFontSpec fontSpec = (AttributeFontSpec) o; + return Objects.equals(size, fontSpec.size) && Objects.equals(weight, fontSpec.weight); + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), size, weight); + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/font/FontParser.java @@ -0,0 +1,140 @@ +/* + * MIT License + * + * Copyright (c) 2021-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.font; + +import java.awt.*; +import java.util.Locale; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import com.github.weisj.jsvg.attributes.value.PercentageDimension; +import com.github.weisj.jsvg.geometry.size.Length; +import com.github.weisj.jsvg.geometry.size.Percentage; +import com.github.weisj.jsvg.parser.impl.AttributeNode; +import com.github.weisj.jsvg.parser.impl.SeparatorMode; + +public final class FontParser { + private FontParser() {} + + // Todo: font-variant + public static @NotNull AttributeFontSpec parseFontSpec(@NotNull AttributeNode node) { + String[] fontFamilies = node.getStringList("font-family", SeparatorMode.COMMA_ONLY); + canonicalizeFontFamily(fontFamilies); + + // Todo: https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight#fallback_weights + @Nullable FontWeight weight = parseWeight(node); + @Nullable FontSize size = parseFontSize(node); + @Nullable Length sizeAdjust = parseSizeAdjust(node); + @Nullable FontStyle style = parseFontStyle(node); + @NotNull Percentage stretch = parseStretch(node); + + return new AttributeFontSpec(fontFamilies, style, sizeAdjust, stretch, size, weight); + } + + private static @NotNull String stripQuotes(@NotNull String str, char quoteChar) { + String quoteStr = String.valueOf(quoteChar); + if (str.length() > 2 && str.startsWith(quoteStr) && str.endsWith(quoteStr)) { + return str.substring(1, str.length() - 1); + } + return str; + } + + private static void canonicalizeFontFamily(@NotNull String[] fontFamilies) { + for (int i = 0; i < fontFamilies.length; i++) { + String family = fontFamilies[i].toLowerCase(Locale.US); + switch (family) { + case "sans-serif": + family = Font.SANS_SERIF; + break; + case "serif": + family = Font.SERIF; + break; + case "monospace": + family = Font.MONOSPACED; + break; + default: + family = stripQuotes(family, '\''); + family = stripQuotes(family, '"'); + break; + } + fontFamilies[i] = family; + } + } + + public static @Nullable FontWeight parseWeight(@NotNull AttributeNode node) { + final String fontWeightKey = "font-weight"; + FontWeight weight = node.getEnum(fontWeightKey, PredefinedFontWeight.Number); + if (weight == PredefinedFontWeight.Number) { + if (node.hasAttribute(fontWeightKey)) { + weight = new NumberFontWeight( + Math.max(1, Math.min(1000, node.getFloat(fontWeightKey, + PredefinedFontWeight.NORMAL_WEIGHT)))); + } else { + weight = null; + } + } + return weight; + } + + public static @NotNull Percentage parseStretch(@NotNull AttributeNode node) { + FontStretch stretch = node.getEnum("font-stretch", FontStretch.Percentage); + return stretch == FontStretch.Percentage + ? node.parser().parsePercentage(node.getValue("font-stretch"), + Percentage.UNSPECIFIED, 0.5f, 2f) + : stretch.percentage(); + } + + public static @Nullable FontSize parseFontSize(@NotNull AttributeNode node) { + FontSize fontSize = node.getEnum("font-size", PredefinedFontSize.Number); + if (fontSize == PredefinedFontSize.Number) { + Length size = node.getLength("font-size", PercentageDimension.CUSTOM, Length.UNSPECIFIED); + fontSize = size.isSpecified() + ? new LengthFontSize(size) + : null; + } + return fontSize; + } + + public static @Nullable Length parseSizeAdjust(@NotNull AttributeNode node) { + return node.getLength("font-size-adjust", PercentageDimension.NONE); + } + + static @Nullable FontStyle parseFontStyle(@NotNull AttributeNode node) { + FontStyle style = null; + String styleStr = node.getValue("font-style"); + if ("normal".equalsIgnoreCase(styleStr)) { + style = FontStyle.normal(); + } else if ("italic".equalsIgnoreCase(styleStr)) { + style = FontStyle.italic(); + } else if (styleStr != null && styleStr.startsWith("oblique")) { + String[] comps = styleStr.split(" ", 2); + if (comps.length == 2) { + style = new FontStyle.Oblique( + node.parser().parseAngle(comps[1], FontStyle.Oblique.DEFAULT_ANGLE)); + } else { + style = FontStyle.oblique(); + } + } + return style; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/font/FontResolver.java @@ -0,0 +1,164 @@ +/* + * MIT License + * + * Copyright (c) 2021-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.font; + +import java.awt.*; +import java.awt.font.TextAttribute; +import java.awt.geom.AffineTransform; +import java.text.AttributedCharacterIterator; +import java.util.*; +import java.util.List; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.renderer.MeasureContext; + +public final class FontResolver { + private FontResolver() {} + + public static void clearFontCache() { + FontCache.INSTANCE.cache.clear(); + } + + public static @NotNull SVGFont resolve(@NotNull MeasurableFontSpec fontSpec, + @NotNull MeasureContext measureContext, @NotNull String defaultFontFamily) { + FontCache.CacheKey key = new FontCache.CacheKey(fontSpec, measureContext); + SVGFont cachedFont = FontCache.INSTANCE.cache.get(key); + if (cachedFont != null) return cachedFont; + SVGFont resolvedFont = resolveWithoutCache(fontSpec, measureContext, defaultFontFamily); + FontCache.INSTANCE.cache.put(key, resolvedFont); + return resolvedFont; + } + + public static @NotNull SVGFont resolveWithoutCache(@NotNull MeasurableFontSpec fontSpec, + @NotNull MeasureContext measureContext, @NotNull String defaultFontFamily) { + String family = findSupportedFontFamily(fontSpec, defaultFontFamily); + + FontStyle style = fontSpec.style(); + + float weight = cssWeightToAwtWeight(fontSpec.currentWeight()); + float size = fontSpec.effectiveSize(measureContext); + float stretch = fontSpec.stretch().orElseIfUnspecified(1).value(); + + Map attributes = new HashMap<>(5, 1f); + attributes.put(TextAttribute.FAMILY, family); + attributes.put(TextAttribute.SIZE, size); + attributes.put(TextAttribute.WEIGHT, weight); + attributes.put(TextAttribute.WIDTH, stretch); + + + if (style instanceof FontStyle.Normal) { + attributes.put(TextAttribute.POSTURE, TextAttribute.POSTURE_REGULAR); + } else if (style instanceof FontStyle.Italic) { + attributes.put(TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE); + } else { + AffineTransform transform = style.transform(); + if (transform != null) attributes.put(TextAttribute.TRANSFORM, transform); + } + + Font font = new Font(attributes); + return new AWTSVGFont(font); + } + + private static float cssWeightToAwtWeight(float weight) { + int normalWeight = PredefinedFontWeight.NORMAL_WEIGHT; + float currentWeight = weight; + if (currentWeight > normalWeight) { + // The bold weight for css and awt differ. We compensate for this difference to ensure + // that bold css fonts correspond to bold awt fonts, as this is the most commonly supported + // font variation. + float awtWeightCompensationFactor = + (TextAttribute.WEIGHT_BOLD * normalWeight) / PredefinedFontWeight.BOLD_WEIGHT; + currentWeight *= awtWeightCompensationFactor; + } + return currentWeight / normalWeight; + } + + private static @NotNull String findSupportedFontFamily(@NotNull MeasurableFontSpec fontSpec, + @NotNull String defaultFontFamily) { + String[] families = fontSpec.families(); + for (String family : families) { + if (FontFamiliesCache.INSTANCE.isSupportedFontFamily(family)) return family; + } + return defaultFontFamily; + } + + public static @NotNull List<@NotNull String> supportedFonts() { + return Collections.unmodifiableList(Arrays.asList(FontFamiliesCache.INSTANCE.supportedFonts)); + } + + @SuppressWarnings("ImmutableEnumChecker") + private enum FontFamiliesCache { + INSTANCE; + + private final @NotNull String[] supportedFonts; + + FontFamiliesCache() { + supportedFonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames(); + } + + boolean isSupportedFontFamily(final @NotNull String fontName) { + for (String supportedFont : supportedFonts) { + if (supportedFont.equalsIgnoreCase(fontName)) return true; + } + return false; + } + } + + @SuppressWarnings("ImmutableEnumChecker") + private enum FontCache { + INSTANCE; + + private final HashMap cache = new HashMap<>(); + + private static final class CacheKey { + private final @NotNull MeasurableFontSpec spec; + private final @NotNull MeasureContext context; + + private CacheKey(@NotNull MeasurableFontSpec spec, @NotNull MeasureContext context) { + this.spec = spec; + this.context = context; + } + + @Override + public String toString() { + return "CacheKey{" + + "spec=" + spec + + ", context=" + context + + '}'; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof CacheKey)) return false; + CacheKey cacheKey = (CacheKey) o; + return spec.equals(cacheKey.spec) && context.equals(cacheKey.context); + } + + @Override + public int hashCode() { + return Objects.hash(spec, context); + } + } + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/font/FontSize.java @@ -0,0 +1,31 @@ +/* + * MIT License + * + * Copyright (c) 2021-2024 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.font; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.geometry.size.Length; + +public interface FontSize { + @NotNull + Length size(@NotNull Length parentSize); +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/font/FontSpec.java @@ -0,0 +1,74 @@ +/* + * MIT License + * + * Copyright (c) 2021-2024 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.font; + +import java.util.Arrays; +import java.util.Objects; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import com.github.weisj.jsvg.geometry.size.Length; +import com.github.weisj.jsvg.geometry.size.Percentage; + +public class FontSpec { + protected final @NotNull String[] families; + protected final @Nullable FontStyle style; + protected final @Nullable Length sizeAdjust; + protected final @NotNull Percentage stretch; + + FontSpec(@NotNull String[] families, @Nullable FontStyle style, @Nullable Length sizeAdjust, + @NotNull Percentage stretch) { + this.families = families; + this.style = style; + this.sizeAdjust = sizeAdjust; + this.stretch = stretch; + } + + @Override + public String toString() { + return "FontSpec{" + + "families=" + Arrays.toString(families) + + ", style=" + style + + ", sizeAdjust=" + sizeAdjust + + ", stretch=" + stretch + + '}'; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof FontSpec)) return false; + FontSpec fontSpec = (FontSpec) o; + return Objects.equals(stretch, fontSpec.stretch) + && Arrays.equals(families, fontSpec.families) + && Objects.equals(style, fontSpec.style) + && Objects.equals(sizeAdjust, fontSpec.sizeAdjust); + } + + @Override + public int hashCode() { + int result = Objects.hash(style, sizeAdjust, stretch); + result = 31 * result + Arrays.hashCode(families); + return result; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/font/FontStretch.java @@ -0,0 +1,68 @@ +/* + * MIT License + * + * Copyright (c) 2021-2024 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.font; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.attributes.HasMatchName; +import com.github.weisj.jsvg.geometry.size.Percentage; + +public enum FontStretch implements HasMatchName { + Normal(1f), + UltraCondensed(0.5f, "ultra-condensed"), + ExtraCondensed(0.625f, "extra-condensed"), + Condensed(0.75f, "condensed"), + SemiCondensed(0.875f, "semi-condensed"), + SemiExpanded(1.125f, "semi-expanded"), + Expanded(1.25f), + ExtraExpanded(1.5f, "extra-expanded"), + UltraExpanded(2f, "ultra-expanded"), + /** + * Allowed values range from 50% to 200%. + */ + Percentage(-1); + + private final @NotNull Percentage percentage; + private final @NotNull String matchName; + + FontStretch(float percentage, @NotNull String matchName) { + this.percentage = new Percentage(percentage); + this.matchName = matchName; + } + + FontStretch(float percentage) { + this.percentage = new Percentage(percentage); + this.matchName = name(); + } + + @Override + public @NotNull String matchName() { + return matchName; + } + + public @NotNull Percentage percentage() { + if (this == Percentage) { + throw new UnsupportedOperationException("Percentage needs to be computed manually"); + } + return percentage; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/font/FontStyle.java @@ -0,0 +1,133 @@ +/* + * MIT License + * + * Copyright (c) 2021-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.font; + +import java.awt.geom.AffineTransform; +import java.util.Objects; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import com.github.weisj.jsvg.annotations.Sealed; +import com.github.weisj.jsvg.geometry.size.Angle; +import com.github.weisj.jsvg.geometry.size.AngleUnit; + +/** + * This abstract class shouldn't be extended besides those constants. + */ +@Sealed(permits = {FontStyle.Normal.class, FontStyle.Italic.class, FontStyle.Oblique.class}) +abstract class FontStyle { + + private FontStyle() {} + + public @Nullable AffineTransform transform() { + return null; + } + + public static @NotNull FontStyle normal() { + return Normal.INSTANCE; + } + + public static @NotNull FontStyle italic() { + return Italic.INSTANCE; + } + + public static @NotNull FontStyle oblique() { + return Oblique.DEFAULT; + } + + public static @NotNull FontStyle oblique(@NotNull Angle angle) { + return new Oblique(angle); + } + + static final class Normal extends FontStyle { + private static final @NotNull FontStyle.Normal INSTANCE = new Normal(); + + @Override + public String toString() { + return "Normal"; + } + + @Override + public boolean equals(Object obj) { + return obj instanceof Normal; + } + + @Override + public int hashCode() { + return Normal.class.hashCode(); + } + } + + static final class Italic extends FontStyle { + private static final @NotNull FontStyle.Italic INSTANCE = new Italic(); + + @Override + public String toString() { + return "Italic"; + } + + @Override + public boolean equals(Object obj) { + return obj instanceof Italic; + } + + @Override + public int hashCode() { + return Italic.class.hashCode(); + } + } + + static final class Oblique extends FontStyle { + public static final @NotNull Angle DEFAULT_ANGLE = new Angle(AngleUnit.Deg, 14); + public static final @NotNull FontStyle.Oblique DEFAULT = new Oblique(DEFAULT_ANGLE); + + private final @NotNull Angle angle; + + public Oblique(@NotNull Angle angle) { + this.angle = angle; + } + + @Override + public @NotNull AffineTransform transform() { + return AffineTransform.getShearInstance(-angle.radians(), 0); + } + + @Override + public String toString() { + return "Oblique{" + angle + '}'; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof Oblique)) return false; + Oblique that = (Oblique) o; + return angle.equals(that.angle); + } + + @Override + public int hashCode() { + return Objects.hashCode(angle); + } + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/font/FontWeight.java @@ -0,0 +1,29 @@ +/* + * MIT License + * + * Copyright (c) 2021 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.font; + +import com.google.errorprone.annotations.Immutable; + +@Immutable +interface FontWeight { + int weight(int parentWeight); +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/font/LengthFontSize.java @@ -0,0 +1,59 @@ +/* + * MIT License + * + * Copyright (c) 2021-2024 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.font; + +import java.util.Objects; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.geometry.size.Length; + +public final class LengthFontSize implements FontSize { + private final @NotNull Length size; + + public LengthFontSize(@NotNull Length size) { + this.size = size; + } + + @Override + public @NotNull Length size(@NotNull Length parentSize) { + return size; + } + + @Override + public String toString() { + return "LengthFontSize{size=" + size + '}'; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof LengthFontSize)) return false; + LengthFontSize that = (LengthFontSize) o; + return size.equals(that.size); + } + + @Override + public int hashCode() { + return Objects.hashCode(size); + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/font/MeasurableFontSpec.java @@ -0,0 +1,143 @@ +/* + * MIT License + * + * Copyright (c) 2021-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.font; + +import java.util.Arrays; +import java.util.Objects; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import com.github.weisj.jsvg.geometry.size.Length; +import com.github.weisj.jsvg.geometry.size.Percentage; +import com.github.weisj.jsvg.geometry.size.Unit; +import com.github.weisj.jsvg.renderer.MeasureContext; + +public final class MeasurableFontSpec extends FontSpec { + private final int currentWeight; + private final @NotNull Length currentSize; + + MeasurableFontSpec(@NotNull String[] families, @Nullable FontStyle style, @Nullable Length sizeAdjust, + @NotNull Percentage stretch, int currentWeight, @NotNull Length currentSize) { + super(families, style, sizeAdjust, stretch); + this.currentWeight = currentWeight; + this.currentSize = currentSize; + } + + public static @NotNull MeasurableFontSpec createDefault() { + return new MeasurableFontSpec( + // Ensure there is always a valid family available. + new String[] {SVGFont.defaultFontFamily()}, + FontStyle.normal(), + null, + FontStretch.Normal.percentage(), + PredefinedFontWeight.NORMAL_WEIGHT, + Unit.RAW.valueOf(SVGFont.defaultFontSize())); + } + + public @NotNull String[] families() { + return families; + } + + public @NotNull FontStyle style() { + assert style != null; + return style; + } + + public @NotNull Percentage stretch() { + return stretch; + } + + public int currentWeight() { + return currentWeight; + } + + public float emSize(@NotNull MeasureContext context) { + return currentSize.resolveFontSize(context); + } + + public float effectiveSize(@NotNull MeasureContext context) { + // TODO: Choose the size of the font so that its lowercase letters + // (as determined by the x-height of the font) + // are the specified number times the font-size. + float emSize = emSize(context); + if (sizeAdjust != null) { + return SVGFont.emFromEx(emSize * sizeAdjust.resolveFontSize(context)); + } + return emSize; + } + + public @NotNull MeasurableFontSpec withFontSize(@Nullable FontSize size, @Nullable Length sizeAdjust) { + if (size == null && sizeAdjust == null) return this; + return new MeasurableFontSpec(families, style, sizeAdjust != null ? sizeAdjust : this.sizeAdjust, stretch, + currentWeight, size != null ? size.size(currentSize) : this.currentSize); + } + + public @NotNull MeasurableFontSpec derive(@Nullable AttributeFontSpec other) { + if (other == null) return this; + String[] newFamilies = other.families != null && other.families.length > 0 + ? other.families + : this.families; + FontStyle newStyle = other.style != null + ? other.style + : this.style; + int newWeight = other.weight() != null + ? other.weight().weight(currentWeight) + : this.currentWeight; + Length newSize = other.size() != null + ? other.size().size(currentSize) + : this.currentSize; + Length newSizeAdjust = other.sizeAdjust != null + ? other.sizeAdjust + : this.sizeAdjust; + Percentage newStretch = other.stretch.isSpecified() + ? other.stretch + : this.stretch; + return new MeasurableFontSpec(newFamilies, newStyle, newSizeAdjust, newStretch, newWeight, newSize); + } + + @Override + public String toString() { + return "MeasurableFontSpec{" + + "families=" + Arrays.toString(families) + + ", style=" + style + + ", sizeAdjust=" + sizeAdjust + + ", stretch=" + stretch + + ", currentWeight=" + currentWeight + + ", currentSize=" + currentSize + + '}'; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof MeasurableFontSpec)) return false; + if (!super.equals(o)) return false; + MeasurableFontSpec fontSpec = (MeasurableFontSpec) o; + return currentWeight == fontSpec.currentWeight && currentSize.equals(fontSpec.currentSize); + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), currentWeight, currentSize); + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/font/NumberFontWeight.java @@ -0,0 +1,56 @@ +/* + * MIT License + * + * Copyright (c) 2021-2023 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.font; + +import com.google.errorprone.annotations.Immutable; + +@Immutable +public final class NumberFontWeight implements FontWeight { + private final float weight; + + public NumberFontWeight(float weight) { + this.weight = weight; + } + + @Override + public int weight(int parentWeight) { + return (int) weight; + } + + @Override + public String toString() { + return "NumberFontWeight{weight=" + weight + '}'; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof NumberFontWeight)) return false; + NumberFontWeight that = (NumberFontWeight) o; + return weight == that.weight; + } + + @Override + public int hashCode() { + return Float.hashCode(weight); + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/font/PredefinedFontSize.java @@ -0,0 +1,67 @@ +/* + * MIT License + * + * Copyright (c) 2021-2024 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.font; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.attributes.HasMatchName; +import com.github.weisj.jsvg.geometry.size.Length; +import com.github.weisj.jsvg.geometry.size.Unit; + +public enum PredefinedFontSize implements HasMatchName, FontSize { + xxSmall("xx-small", 3f / 5f), + xSmall("x-small", 3f / 4f), + small(8f / 9f), + medium(1f), + large(6f / 5f), + xLarge("x-large", 3f / 2f), + xxLarge("xx-large", 2f), + xxxLarge("xxx-large", 3f), + larger(1.3f), + smaller(0.7f), + Number(0); + + private final @NotNull String matchName; + private final float scalingFactor; + + PredefinedFontSize(@NotNull String matchName, float scalingFactor) { + this.matchName = matchName; + this.scalingFactor = scalingFactor; + } + + PredefinedFontSize(float scalingFactor) { + this.scalingFactor = scalingFactor; + this.matchName = name(); + } + + @Override + public @NotNull String matchName() { + return matchName; + } + + @Override + public @NotNull Length size(@NotNull Length parentSize) { + if (this == Number) throw new UnsupportedOperationException("Number font-size needs to parsed explicitly"); + if (this == smaller || this == larger) return parentSize.multiply(scalingFactor); + return Unit.RAW.valueOf(SVGFont.defaultFontSize() * scalingFactor); + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/font/PredefinedFontWeight.java @@ -0,0 +1,65 @@ +/* + * MIT License + * + * Copyright (c) 2021 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.font; + +import com.google.errorprone.annotations.Immutable; + +@Immutable +public enum PredefinedFontWeight implements FontWeight { + Normal { + @Override + public int weight(int parentWeight) { + return NORMAL_WEIGHT; + } + }, + Bold { + @Override + public int weight(int parentWeight) { + return BOLD_WEIGHT; + } + }, + Bolder { + @Override + public int weight(int parentWeight) { + if (parentWeight < 400) return 400; + if (parentWeight < 600) return 600; + return Math.max(parentWeight, 900); + } + }, + Lighter { + @Override + public int weight(int parentWeight) { + if (parentWeight > 700) return 700; + if (parentWeight > 500) return 400; + return Math.min(parentWeight, 100); + } + }, + Number { + @Override + public int weight(int parentWeight) { + throw new UnsupportedOperationException("Number needs to be parsed explicitly"); + } + }; + + public static final int NORMAL_WEIGHT = 400; + public static final int BOLD_WEIGHT = 700; +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/font/SVGFont.java @@ -0,0 +1,74 @@ +/* + * MIT License + * + * Copyright (c) 2021-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.font; + +import java.awt.*; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.nodes.text.Glyph; + +public interface SVGFont { + + static float defaultFontSize() { + return 10f; + } + + static @NotNull String defaultFontFamily() { + return Font.SERIF; + } + + static float exFromEm(float em) { + // The spec allows to treat ex as 0.5 of the em value. + return em / 2f; + } + + static float emFromEx(float ex) { + return 2f * ex; + } + + @NotNull + Glyph codepointGlyph(@NotNull String codepoint); + + @NotNull + String family(); + + int size(); + + float effectiveExHeight(); + + float effectiveEmHeight(); + + float mathematicalBaseline(); + + float hangingBaseline(); + + float romanBaseline(); + + float centerBaseline(); + + float middleBaseline(); + + float textUnderBaseline(); + + float textOverBaseline(); +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/font/package-info.java @@ -0,0 +1,3 @@ +@org.osgi.annotation.bundle.Export(attribute = "x-internal") +@aQute.bnd.annotation.jpms.ExportTo("com.github.weisj.jsvg.javafx") +package com.github.weisj.jsvg.attributes.font; --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/package-info.java @@ -0,0 +1,3 @@ +@org.osgi.annotation.bundle.Export(attribute = "x-internal") +@aQute.bnd.annotation.jpms.ExportTo("com.github.weisj.jsvg.javafx") +package com.github.weisj.jsvg.attributes; --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/stroke/LineCap.java @@ -0,0 +1,48 @@ +/* + * MIT License + * + * Copyright (c) 2021-2023 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.stroke; + +import java.awt.*; + +import org.intellij.lang.annotations.MagicConstant; + +import com.github.weisj.jsvg.attributes.Default; + +public enum LineCap { + @Default + Butt(BasicStroke.CAP_BUTT), + Square(BasicStroke.CAP_SQUARE), + Round(BasicStroke.CAP_ROUND); + + private final int awtCode; + + LineCap(int awtCode) { + this.awtCode = awtCode; + } + + @MagicConstant( + intValues = {BasicStroke.CAP_BUTT, BasicStroke.CAP_SQUARE, BasicStroke.CAP_ROUND} + ) + public int awtCode() { + return awtCode; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/stroke/LineJoin.java @@ -0,0 +1,48 @@ +/* + * MIT License + * + * Copyright (c) 2021-2023 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.stroke; + +import java.awt.*; + +import org.intellij.lang.annotations.MagicConstant; + +import com.github.weisj.jsvg.attributes.Default; + +public enum LineJoin { + @Default + Miter(BasicStroke.JOIN_MITER), + Round(BasicStroke.JOIN_ROUND), + Bevel(BasicStroke.JOIN_BEVEL); + + private final int awtCode; + + LineJoin(int awtCode) { + this.awtCode = awtCode; + } + + @MagicConstant( + intValues = {BasicStroke.JOIN_BEVEL, BasicStroke.JOIN_ROUND, BasicStroke.JOIN_MITER} + ) + public int awtCode() { + return awtCode; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/stroke/StrokeResolver.java @@ -0,0 +1,76 @@ +/* + * MIT License + * + * Copyright (c) 2021-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.stroke; + +import java.awt.*; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.attributes.value.LengthValue; +import com.github.weisj.jsvg.geometry.size.Length; +import com.github.weisj.jsvg.renderer.MeasureContext; +import com.github.weisj.jsvg.renderer.impl.context.StrokeContext; + +public final class StrokeResolver { + private StrokeResolver() {} + + // https://svgwg.org/svg2-draft/painting.html#StrokeMiterlimitProperty + public static @NotNull Stroke resolve(float pathLengthFactor, @NotNull MeasureContext measureContext, + @NotNull StrokeContext context) { + LengthValue strokeWidth = context.strokeWidth; + LineCap lineCap = context.lineCap; + LineJoin lineJoin = context.lineJoin; + float miterLimit = context.miterLimit; + + Length[] dashPattern = context.dashPattern; + LengthValue dashOffset = context.dashOffset; + + assert strokeWidth != null; + assert lineCap != null; + assert lineJoin != null; + assert Length.isSpecified(miterLimit); + assert dashOffset != null; + assert dashPattern != null; + + // In practice, any miter join will exceed a miter limit between 0 and 1. + miterLimit = Math.max(1, miterLimit); + + float[] dashes = new float[dashPattern.length]; + float offsetLength = 0; + for (int i = 0; i < dashes.length; i++) { + float dash = dashPattern[i].resolve(measureContext) * pathLengthFactor; + offsetLength += dash; + dashes[i] = dash; + } + + float phase = dashOffset.resolve(measureContext) * pathLengthFactor; + if (phase < 0) phase += offsetLength; + + if (dashes.length == 0) { + return new BasicStroke(strokeWidth.resolve(measureContext), lineCap.awtCode(), lineJoin.awtCode(), + miterLimit); + } else { + return new BasicStroke(strokeWidth.resolve(measureContext), lineCap.awtCode(), lineJoin.awtCode(), + miterLimit, dashes, phase); + } + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/stroke/package-info.java @@ -0,0 +1,3 @@ +@org.osgi.annotation.bundle.Export(attribute = "x-internal") +@aQute.bnd.annotation.jpms.ExportTo("com.github.weisj.jsvg.javafx") +package com.github.weisj.jsvg.attributes.stroke; --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/text/DominantBaseline.java @@ -0,0 +1,121 @@ +/* + * MIT License + * + * Copyright (c) 2022-2023 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.text; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.attributes.Default; +import com.github.weisj.jsvg.attributes.HasMatchName; + +public enum DominantBaseline implements HasMatchName { + /** + * If this property occurs on a element, then the computed value depends on the value of the writing-mode + * attribute. + *

+ * If the writing-mode is horizontal, then the value of the dominant-baseline component is alphabetic. + * Otherwise, if the writing-mode is vertical, then the value of the dominant-baseline component is central. + *

+ * If this property occurs on a 'tspan', 'tref', 'altGlyph', or 'textPath' element, then the dominant-baseline + * and the baseline-table components remain the same as those of the parent text content element. + *

+ * If the computed baseline-shift value actually shifts the baseline, then the baseline-table font-size component + * is set to the value of the font-size attribute on the element on which the dominant-baseline attribute occurs, + * otherwise the baseline-table font-size remains the same as that of the element. + *

+ * If there is no parent text content element, the scaled-baseline-table value is constructed as above for 'text' + * elements. + */ + @Default + Auto, + /** + * The baseline-identifier for the dominant-baseline is set to be ideographic, the derived baseline-table is + * constructed using the ideographic baseline-table in the font, and the baseline-table font-size is changed to the + * value of the font-size attribute on this element. + */ + Ideographic, + /** + * The baseline-identifier for the dominant-baseline is set to be alphabetic, the derived baseline-table is + * constructed using the alphabetic baseline-table in the font, and the baseline-table font-size is changed to the + * value of the font-size attribute on this element. + */ + Alphabetic, + /** + * The baseline-identifier for the dominant-baseline is set to be hanging, the derived baseline-table is + * constructed using the hanging baseline-table in the font, and the baseline-table font-size is changed to the + * value of the font-size attribute on this element. + */ + Hanging, + /** + * The baseline-identifier for the dominant-baseline is set to be mathematical, the derived baseline-table is + * constructed using the mathematical baseline-table in the font, and the baseline-table font-size is changed to + * the value of the font-size attribute on this element. + */ + Mathematical, + /** + * The baseline-identifier for the dominant-baseline is set to be central. The derived baseline-table is + * constructed from the defined baselines in a baseline-table in the font. That font baseline-table is chosen + * using the following priority order of baseline-table names: ideographic, alphabetic, hanging, mathematical. + * The baseline-table font-size is changed to the value of the font-size attribute on this element. + */ + Central, + /** + * The baseline-identifier for the dominant-baseline is set to be middle. The derived baseline-table is + * constructed from the defined baselines in a baseline-table in the font. That font baseline-table is chosen + * using the following priority order of baseline-table names: alphabetic, ideographic, hanging, mathematical. + * The baseline-table font-size is changed to the value of the font-size attribute on this element. + */ + Middle, + /** + * The baseline-identifier for the dominant-baseline is set to be text-after-edge. The derived baseline-table is + * constructed from the defined baselines in a baseline-table in the font. The choice of which font baseline-table + * to use from the baseline-tables in the font is browser dependent. The baseline-table font-size is changed to + * the value of the font-size attribute on this element. + */ + TextAfterEdge("text-after-edge"), + TextBottom("text-bottom"), + /** + * The baseline-identifier for the dominant-baseline is set to be text-before-edge. The derived baseline-table is + * constructed from the defined baselines in a baseline-table in the font. The choice of which baseline-table to + * use from the baseline-tables in the font is browser dependent. The baseline-table font-size is changed to the + * value of the font-size attribute on this element. + */ + TextBeforeEdge("text-before-edge"), + /** + * This value uses the top of the em box as the baseline. + */ + TextTop("text-top"); + + private final @NotNull String matchName; + + DominantBaseline(@NotNull String matchName) { + this.matchName = matchName; + } + + DominantBaseline() { + this.matchName = name(); + } + + @Override + public @NotNull String matchName() { + return matchName; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/text/GlyphRenderMethod.java @@ -0,0 +1,37 @@ +/* + * MIT License + * + * Copyright (c) 2021 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.text; + +public enum GlyphRenderMethod { + /** + * This value indicates that the characters should be rendered so that they are not stretched or warped. + * The characters are rotated, scaled and stretched when they are rendered. + * As a result, for fonts with connected characters (e.g. cursive fonts), the connections may not align properly + * when text is rendered along the path. + */ + Align, + /** + * This value indicates that the character outlines will be converted into paths, and then stretched and possibly + * warped. With this approach, connected characters, such as in cursive fonts, will maintain their connections. + */ + Stretch +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/text/LengthAdjust.java @@ -0,0 +1,30 @@ +/* + * MIT License + * + * Copyright (c) 2021-2022 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.text; + +import com.github.weisj.jsvg.attributes.Default; + +public enum LengthAdjust { + @Default + Spacing, + SpacingAndGlyphs +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/text/Side.java @@ -0,0 +1,34 @@ +/* + * MIT License + * + * Copyright (c) 2021 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.text; + +public enum Side { + /** + * This value places the text on the left side of the path (relative to the path direction). + */ + Left, + /** + * This value places the text on the right side of the path (relative to the path direction). + * This effectively reverses the path direction. + */ + Right +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/text/Spacing.java @@ -0,0 +1,35 @@ +/* + * MIT License + * + * Copyright (c) 2021 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.text; + +public enum Spacing { + /** + * This value indicates that the user agent should use text-on-a-path layout algorithms to adjust + * the spacing between typographic characters in order to achieve visually appealing results. + */ + Auto, + /** + * This value indicates that the typographic characters should be rendered exactly according to + * the spacing rules as specified by the layout rules for text-on-a-path. + */ + Exact +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/text/TextAnchor.java @@ -0,0 +1,28 @@ +/* + * MIT License + * + * Copyright (c) 2021 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.text; + +public enum TextAnchor { + Start, + Middle, + End +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/text/package-info.java @@ -0,0 +1,3 @@ +@org.osgi.annotation.bundle.Export(attribute = "x-internal") +@aQute.bnd.annotation.jpms.ExportTo("com.github.weisj.jsvg.javafx") +package com.github.weisj.jsvg.attributes.text; --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/transform/TransformBox.java @@ -0,0 +1,49 @@ +/* + * MIT License + * + * Copyright (c) 2021-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.transform; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.attributes.HasMatchName; + +/** + * Represents possible values of the transform-box rule. It determines the box relative to which a transform-origin + * is computed. + */ +public enum TransformBox implements HasMatchName { + FillBox("fill-box"), + StrokeBox("stroke-box"), + ViewBox("view-box"), + // Other permitted values content-box and border-box pertain only to HTML elements. + ; + + private final @NotNull String matchName; + + TransformBox(@NotNull String matchName) { + this.matchName = matchName; + } + + @Override + public @NotNull String matchName() { + return matchName; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/transform/TransformPart.java @@ -0,0 +1,283 @@ +/* + * MIT License + * + * Copyright (c) 2024-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.transform; + +import java.awt.geom.AffineTransform; +import java.util.Arrays; + +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.attributes.HasMatchName; +import com.github.weisj.jsvg.geometry.size.Length; +import com.github.weisj.jsvg.geometry.util.GeometryUtil; +import com.github.weisj.jsvg.renderer.MeasureContext; + +public final class TransformPart { + + public enum TransformType implements HasMatchName { + MATRIX, + TRANSLATE, + TRANSLATE_X("translateX"), + TRANSLATE_Y("translateY"), + SCALE, + SCALE_X("scaleX"), + SCALE_Y("scaleY"), + ROTATE, + SKEW, + SKEW_X("skewX"), + SKEW_Y("skewY"); + + private final @NotNull String matchName; + + TransformType(@NotNull String matchName) { + this.matchName = matchName; + } + + TransformType() { + this.matchName = name(); + } + + @Override + public @NotNull String matchName() { + return matchName; + } + + TransformType interpolationType() { + switch (this) { + case TRANSLATE_X: + case TRANSLATE_Y: + return TRANSLATE; + case SCALE_X: + case SCALE_Y: + return SCALE; + case SKEW_X: + case SKEW_Y: + return SKEW; + default: + return this; + } + } + } + + private static final TransformPart IDENTITY_MATRIX = new TransformPart(TransformType.MATRIX, new Length[] { + Length.ONE, Length.ZERO, Length.ZERO, + Length.ONE, Length.ZERO, Length.ZERO + }); + private static final TransformPart IDENTITY_TRANSLATE = + new TransformPart(TransformType.TRANSLATE, new Length[] {Length.ZERO, Length.ZERO}); + private static final TransformPart IDENTITY_SCALE = + new TransformPart(TransformType.SCALE, new Length[] {Length.ONE, Length.ONE}); + + private static final TransformPart IDENTITY_ROTATE = + new TransformPart(TransformType.ROTATE, new Length[] {Length.ZERO, Length.ZERO, Length.ZERO}); + + private static final TransformPart IDENTITY_SKEW = + new TransformPart(TransformType.ROTATE, new Length[] {Length.ZERO, Length.ZERO}); + + private final TransformType type; + private final Length[] values; + + public TransformPart(TransformType type, @NotNull Length @NotNull [] values) { + this.type = type; + this.values = values; + } + + public static @NotNull TransformPart identityOfType(@NotNull TransformType type) { + switch (type) { + case MATRIX: + return IDENTITY_MATRIX; + case TRANSLATE: + case TRANSLATE_X: + case TRANSLATE_Y: + return IDENTITY_TRANSLATE; + case SCALE: + case SCALE_X: + case SCALE_Y: + return IDENTITY_SCALE; + case ROTATE: + return IDENTITY_ROTATE; + case SKEW: + case SKEW_X: + case SKEW_Y: + return IDENTITY_SKEW; + default: + throw new IllegalArgumentException("Unknown transform type: " + type); + } + } + + private static float getEntry(@NotNull TransformPart part, int index, float fallback, + @NotNull MeasureContext context) { + if (part.values.length > index) return part.values[index].resolve(context); + return fallback; + } + + public static @NotNull AffineTransform interpolate(@NotNull TransformPart a, @NotNull TransformPart b, + @NotNull MeasureContext measureContext, float t) { + TransformType aType = a.type.interpolationType(); + TransformType bType = b.type.interpolationType(); + if (aType != bType) { + return GeometryUtil.interpolate(a.toTransform(measureContext), b.toTransform(measureContext), t); + } + switch (aType) { + case MATRIX: + return GeometryUtil.interpolate(a.toTransform(measureContext), b.toTransform(measureContext), t); + case TRANSLATE: + case TRANSLATE_X: + case TRANSLATE_Y: + return AffineTransform.getTranslateInstance( + GeometryUtil.lerp(t, + a.values[0].resolve(measureContext), + b.values[0].resolve(measureContext)), + GeometryUtil.lerp(t, + getEntry(a, 1, 0f, measureContext), + getEntry(b, 1, 0f, measureContext))); + case SCALE: + case SCALE_X: + case SCALE_Y: + float aScaleX = a.values[0].resolve(measureContext); + float aScaleY = getEntry(a, 1, aScaleX, measureContext); + float bScaleX = b.values[0].resolve(measureContext); + float bScaleY = getEntry(a, 1, bScaleX, measureContext); + return AffineTransform.getScaleInstance( + GeometryUtil.lerp(t, aScaleX, bScaleX), + GeometryUtil.lerp(t, aScaleY, bScaleY)); + case ROTATE: + return AffineTransform.getRotateInstance( + Math.toRadians(GeometryUtil.lerp(t, + a.values[0].resolve(measureContext), + b.values[0].resolve(measureContext))), + GeometryUtil.lerp(t, + getEntry(a, 1, 0, measureContext), + getEntry(b, 1, 0, measureContext)), + GeometryUtil.lerp(t, + getEntry(a, 2, 0, measureContext), + getEntry(b, 2, 0, measureContext))); + case SKEW: + case SKEW_X: + case SKEW_Y: + return AffineTransform.getShearInstance( + Math.tan(Math.toRadians( + GeometryUtil.lerp(t, + a.values[0].resolve(measureContext), + b.values[0].resolve(measureContext)))), + Math.tan(Math.toRadians( + GeometryUtil.lerp(t, + getEntry(a, 1, 0, measureContext), + getEntry(b, 1, 0, measureContext))))); + default: + throw new IllegalStateException(); + } + } + + public boolean canBeFlattened() { + for (Length value : values) { + if (!value.isAbsolute()) return false; + } + return true; + } + + @Contract(value = "_ -> new", pure = true) + public @NotNull AffineTransform toTransform(@NotNull MeasureContext measureContext) { + return applyToTransform(new AffineTransform(), measureContext); + } + + @Contract(value = "_,_ -> param1", pure = true) + public @NotNull AffineTransform applyToTransform(@NotNull AffineTransform transform, + @NotNull MeasureContext measureContext) { + return applyToTransform(transform, measureContext, 1); + } + + @Contract(value = "_,_,_ -> param1", pure = true) + public @NotNull AffineTransform applyToTransform(@NotNull AffineTransform transform, + @NotNull MeasureContext measureContext, + float progress) { + switch (type) { + case MATRIX: + transform.concatenate(new AffineTransform( + values[0].resolve(measureContext), + values[1].resolve(measureContext), + values[2].resolve(measureContext), + values[3].resolve(measureContext), + values[4].resolve(measureContext), + values[5].resolve(measureContext))); + break; + case TRANSLATE: + transform.translate( + progress * values[0].resolve(measureContext), + progress * values[1].resolve(measureContext)); + break; + case TRANSLATE_X: + transform.translate(values[0].resolve(measureContext), 0); + break; + case TRANSLATE_Y: + transform.translate(0, values[0].resolve(measureContext)); + break; + case SCALE: + if (values.length == 1) { + float scale = values[0].resolve(measureContext); + transform.scale(scale, scale); + } else { + transform.scale(values[0].resolve(measureContext), values[1].resolve(measureContext)); + } + break; + case SCALE_X: + transform.scale(values[0].resolve(measureContext), 1); + break; + case SCALE_Y: + transform.scale(1, values[0].resolve(measureContext)); + break; + case ROTATE: + if (values.length == 1) { + transform.rotate(Math.toRadians(values[0].resolve(measureContext))); + } else { + transform.rotate(Math.toRadians(values[0].resolve(measureContext)), + values[1].resolve(measureContext), + values[2].resolve(measureContext)); + } + break; + case SKEW: + if (values.length == 1) { + transform.shear(Math.tan(Math.toRadians(values[0].resolve(measureContext))), 0); + } else { + transform.shear(Math.tan(Math.toRadians(values[0].resolve(measureContext))), + Math.tan(Math.toRadians(values[1].resolve(measureContext)))); + } + break; + case SKEW_X: + transform.shear(Math.tan(Math.toRadians(values[0].resolve(measureContext))), 0); + break; + case SKEW_Y: + transform.shear(0, Math.tan(Math.toRadians(values[0].resolve(measureContext)))); + break; + } + return transform; + } + + @Override + public String toString() { + return "TransformPart{" + + "type=" + type + + ", values=" + Arrays.toString(values) + + '}'; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/transform/package-info.java @@ -0,0 +1,3 @@ +@org.osgi.annotation.bundle.Export(attribute = "x-internal") +@aQute.bnd.annotation.jpms.ExportTo("com.github.weisj.jsvg.javafx") +package com.github.weisj.jsvg.attributes.transform; --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/value/ColorValue.java @@ -0,0 +1,37 @@ +/* + * MIT License + * + * Copyright (c) 2024-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.value; + +import java.awt.*; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.animation.value.AnimatedColor; +import com.github.weisj.jsvg.annotations.Sealed; +import com.github.weisj.jsvg.paint.impl.RGBColor; +import com.github.weisj.jsvg.renderer.MeasureContext; + +@Sealed(permits = {RGBColor.class, AnimatedColor.class}) +public interface ColorValue { + @NotNull + Color get(@NotNull MeasureContext context); +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/value/ConstantFloat.java @@ -0,0 +1,39 @@ +/* + * MIT License + * + * Copyright (c) 2024-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.value; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.renderer.MeasureContext; + +public final class ConstantFloat implements FloatValue { + private final float value; + + public ConstantFloat(float value) { + this.value = value; + } + + @Override + public float get(@NotNull MeasureContext context) { + return value; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/value/ConstantFloatList.java @@ -0,0 +1,44 @@ +/* + * MIT License + * + * Copyright (c) 2024-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.value; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.renderer.MeasureContext; + +public final class ConstantFloatList implements FloatListValue { + public static final @NotNull FloatListValue EMPTY = new ConstantFloatList(new float[0]); + private final float @NotNull [] value; + + public ConstantFloatList(float @NotNull [] value) { + this.value = value; + } + + @Override + public float @NotNull [] get(@NotNull MeasureContext context) { + return value; + } + + public float[] value() { + return value; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/value/ConstantLengthTransform.java @@ -0,0 +1,51 @@ +/* + * MIT License + * + * Copyright (c) 2024-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.value; + +import java.awt.geom.AffineTransform; +import java.util.Collections; +import java.util.List; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.attributes.transform.TransformPart; +import com.github.weisj.jsvg.renderer.MeasureContext; + +public final class ConstantLengthTransform implements TransformValue { + public static final ConstantLengthTransform IDENTITY = new ConstantLengthTransform(Collections.emptyList()); + public static final ConstantLengthTransform INHERITED = new ConstantLengthTransform(Collections.emptyList()); + + private final @NotNull List<@NotNull TransformPart> parts; + + public ConstantLengthTransform(@NotNull List<@NotNull TransformPart> parts) { + this.parts = parts; + } + + @Override + public @NotNull AffineTransform get(@NotNull MeasureContext context) { + AffineTransform transform = new AffineTransform(); + for (TransformPart part : parts) { + part.applyToTransform(transform, context); + } + return transform; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/value/ConstantTransform.java @@ -0,0 +1,41 @@ +/* + * MIT License + * + * Copyright (c) 2024-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.value; + +import java.awt.geom.AffineTransform; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.renderer.MeasureContext; + +public final class ConstantTransform implements TransformValue { + private final @NotNull AffineTransform value; + + public ConstantTransform(@NotNull AffineTransform value) { + this.value = value; + } + + @Override + public @NotNull AffineTransform get(@NotNull MeasureContext context) { + return value; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/value/ConstantValue.java @@ -0,0 +1,43 @@ +/* + * MIT License + * + * Copyright (c) 2024-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.value; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.renderer.MeasureContext; + +public final class ConstantValue implements Value { + private final T value; + + public ConstantValue(T value) { + this.value = value; + } + + @Override + public T get(@NotNull MeasureContext context) { + return value; + } + + public T get() { + return value; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/value/FloatListValue.java @@ -0,0 +1,34 @@ +/* + * MIT License + * + * Copyright (c) 2024-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.value; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.animation.value.AnimatedFloatList; +import com.github.weisj.jsvg.annotations.Sealed; +import com.github.weisj.jsvg.renderer.MeasureContext; + +@Sealed(permits = {ConstantFloatList.class, AnimatedFloatList.class}) +public interface FloatListValue { + + float @NotNull [] get(@NotNull MeasureContext context); +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/value/FloatValue.java @@ -0,0 +1,34 @@ +/* + * MIT License + * + * Copyright (c) 2024-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.value; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.animation.value.AnimatedFloat; +import com.github.weisj.jsvg.annotations.Sealed; +import com.github.weisj.jsvg.renderer.MeasureContext; + +@Sealed(permits = {ConstantFloat.class, AnimatedFloat.class}) +public interface FloatValue { + + float get(@NotNull MeasureContext context); +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/value/LengthValue.java @@ -0,0 +1,54 @@ +/* + * MIT License + * + * Copyright (c) 2024-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.value; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import com.github.weisj.jsvg.animation.value.AnimatedLength; +import com.github.weisj.jsvg.annotations.Sealed; +import com.github.weisj.jsvg.geometry.size.Length; +import com.github.weisj.jsvg.renderer.MeasureContext; + +@Sealed(permits = {Length.class, AnimatedLength.class}) +public interface LengthValue { + + static @Nullable LengthValue derive(@Nullable LengthValue current, @Nullable LengthValue other) { + if (other == null) return current; + if (current == null) return other; + if (other instanceof AnimatedLength) { + return ((AnimatedLength) other).derive(current); + } + return other; + } + + boolean isConstantlyZero(); + + boolean isConstantlyNonNegative(); + + /** + * Resolve the length to its effective value. + * @param context the measuring context. + * @return the resolved size. + */ + float resolve(@NotNull MeasureContext context); +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/value/PercentageDimension.java @@ -0,0 +1,30 @@ +/* + * MIT License + * + * Copyright (c) 2024 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.value; + +public enum PercentageDimension { + WIDTH, + HEIGHT, + LENGTH, + CUSTOM, + NONE +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/value/PercentageValue.java @@ -0,0 +1,48 @@ +/* + * MIT License + * + * Copyright (c) 2024-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.value; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import com.github.weisj.jsvg.animation.value.AnimatedPercentage; +import com.github.weisj.jsvg.annotations.Sealed; +import com.github.weisj.jsvg.geometry.size.Percentage; +import com.github.weisj.jsvg.renderer.MeasureContext; + +@Sealed(permits = {Percentage.class, AnimatedPercentage.class}) +public interface PercentageValue { + + static @Nullable PercentageValue derive(@Nullable PercentageValue current, @Nullable PercentageValue other) { + if (other == null) return current; + if (current == null) return other; + if (other instanceof AnimatedPercentage) { + return ((AnimatedPercentage) other).derive(current); + } + return other; + } + + float get(@NotNull MeasureContext context); + + @NotNull + PercentageValue multiply(@NotNull PercentageValue other); +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/value/TransformValue.java @@ -0,0 +1,47 @@ +/* + * MIT License + * + * Copyright (c) 2024-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.value; + +import java.awt.geom.AffineTransform; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import com.github.weisj.jsvg.animation.value.AnimatedTransform; +import com.github.weisj.jsvg.annotations.Sealed; +import com.github.weisj.jsvg.renderer.MeasureContext; + +@Sealed(permits = {AnimatedTransform.class, ConstantTransform.class, ConstantLengthTransform.class}) +public interface TransformValue { + + static @Nullable TransformValue derive(@Nullable TransformValue current, @Nullable TransformValue other) { + if (other == null) return current; + if (current == null) return other; + if (other instanceof AnimatedTransform) { + return ((AnimatedTransform) other).derive(current); + } + return other; + } + + @NotNull + AffineTransform get(@NotNull MeasureContext context); +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/value/Value.java @@ -0,0 +1,32 @@ +/* + * MIT License + * + * Copyright (c) 2024-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.attributes.value; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.renderer.MeasureContext; + +public interface Value { + + T get(@NotNull MeasureContext context); + +} --- /dev/null +++ b/src/com/github/weisj/jsvg/attributes/value/package-info.java @@ -0,0 +1,3 @@ +@org.osgi.annotation.bundle.Export(attribute = "x-internal") +@aQute.bnd.annotation.jpms.ExportTo("com.github.weisj.jsvg.javafx") +package com.github.weisj.jsvg.attributes.value; --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/AWTSVGShape.java @@ -0,0 +1,109 @@ +/* + * MIT License + * + * Copyright (c) 2021-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.geometry; + +import java.awt.*; +import java.awt.geom.*; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.attributes.value.ConstantValue; +import com.github.weisj.jsvg.attributes.value.Value; +import com.github.weisj.jsvg.geometry.util.GeometryUtil; +import com.github.weisj.jsvg.renderer.RenderContext; + +public class AWTSVGShape implements SVGShape { + public static final Rectangle2D EMPTY_SHAPE = new Rectangle(); + protected final @NotNull Value<@NotNull T> shapeValue; + private Rectangle2D boundsCache; + private T shapeCache; + + private double pathLength; + + public AWTSVGShape(@NotNull T shape) { + this(new ConstantValue<>(shape)); + } + + public AWTSVGShape(@NotNull Value<@NotNull T> shapeValue) { + this(shapeValue, Double.NaN); + } + + private AWTSVGShape(@NotNull Value<@NotNull T> shapeValue, double pathLength) { + this.shapeValue = shapeValue; + this.pathLength = pathLength; + } + + @Override + public @NotNull T shape(@NotNull RenderContext context, boolean validate) { + if (shapeCache == null || validate) { + shapeCache = shapeValue.get(context.measureContext()); + } + return shapeCache; + } + + @Override + public @NotNull Rectangle2D bounds(@NotNull RenderContext context, boolean validate) { + if (boundsCache == null || validate) { + Shape shape = shape(context, validate); + boundsCache = shape.getBounds2D(); + } + return boundsCache; + } + + @Override + public double pathLength(@NotNull RenderContext context) { + if (Double.isNaN(pathLength)) { + pathLength = computePathLength(context); + } + return pathLength; + } + + private double computePathLength(@NotNull RenderContext context) { + // Optimize shapes for which the computation is simple. + Shape shape = shape(context, false); + if (shape instanceof Rectangle2D) { + Rectangle2D r = (Rectangle2D) shape; + return 2 * (r.getWidth() + r.getHeight()); + } else if (shape instanceof Ellipse2D) { + Ellipse2D e = (Ellipse2D) shape; + double w = e.getWidth(); + double h = e.getHeight(); + if (w == h) return Math.PI * w; + // General ellipse + return SVGEllipse.ellipseCircumference(w / 2f, h / 2f); + } else { + return GeometryUtil.pathLength(shape); + } + } + + @Override + public boolean isClosed(@NotNull RenderContext context) { + Shape shape = shape(context, false); + if (shape instanceof Rectangle2D) { + return true; + } else if (shape instanceof Ellipse2D) { + return true; + } else { + return GeometryUtil.isSingleClosedPath(shape); + } + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/FillRuleAwareAWTSVGShape.java @@ -0,0 +1,44 @@ +/* + * MIT License + * + * Copyright (c) 2021-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.geometry; + +import java.awt.geom.Path2D; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.attributes.value.Value; +import com.github.weisj.jsvg.renderer.RenderContext; +import com.github.weisj.jsvg.renderer.impl.context.RenderContextAccessor; + +public final class FillRuleAwareAWTSVGShape extends AWTSVGShape { + + public FillRuleAwareAWTSVGShape(@NotNull Value shape) { + super(shape); + } + + @Override + public @NotNull Path2D shape(@NotNull RenderContext context, boolean validate) { + Path2D shape = super.shape(context, validate); + shape.setWindingRule(RenderContextAccessor.instance().fillRule(context).awtWindingRule); + return shape; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/SVGCircle.java @@ -0,0 +1,79 @@ +/* + * MIT License + * + * Copyright (c) 2021-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.geometry; + +import java.awt.*; +import java.awt.geom.Ellipse2D; +import java.awt.geom.Rectangle2D; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.attributes.value.LengthValue; +import com.github.weisj.jsvg.renderer.MeasureContext; +import com.github.weisj.jsvg.renderer.RenderContext; + +public final class SVGCircle implements SVGShape { + + private final @NotNull Ellipse2D.Float circle = new Ellipse2D.Float(); + private final @NotNull LengthValue cx; + private final @NotNull LengthValue cy; + private final @NotNull LengthValue r; + + public SVGCircle(@NotNull LengthValue cx, @NotNull LengthValue cy, @NotNull LengthValue r) { + this.cx = cx; + this.cy = cy; + this.r = r; + } + + private void validateShape(@NotNull MeasureContext measureContext) { + float x = cx.resolve(measureContext); + float y = cy.resolve(measureContext); + float rr = r.resolve(measureContext); + circle.setFrame(x - rr, y - rr, 2 * rr, 2 * rr); + } + + @Override + public @NotNull Shape shape(@NotNull RenderContext context, boolean validate) { + if (validate) validateShape(context.measureContext()); + return circle; + } + + @Override + public @NotNull Rectangle2D bounds(@NotNull RenderContext context, boolean validate) { + if (validate) validateShape(context.measureContext()); + return circle.getBounds2D(); + } + + @Override + public double pathLength(@NotNull RenderContext context) { + return circumference(r.resolve(context.measureContext())); + } + + @Override + public boolean isClosed(@NotNull RenderContext context) { + return true; + } + + static double circumference(double radius) { + return 2 * Math.PI * radius; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/SVGEllipse.java @@ -0,0 +1,92 @@ +/* + * MIT License + * + * Copyright (c) 2021-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.geometry; + +import java.awt.*; +import java.awt.geom.Ellipse2D; +import java.awt.geom.Rectangle2D; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.attributes.value.LengthValue; +import com.github.weisj.jsvg.renderer.MeasureContext; +import com.github.weisj.jsvg.renderer.RenderContext; + +public final class SVGEllipse implements SVGShape { + + private final @NotNull Ellipse2D.Float ellipse = new Ellipse2D.Float(); + private final @NotNull LengthValue cx; + private final @NotNull LengthValue cy; + private final @NotNull LengthValue rx; + private final @NotNull LengthValue ry; + + public SVGEllipse(@NotNull LengthValue cx, @NotNull LengthValue cy, @NotNull LengthValue rx, + @NotNull LengthValue ry) { + this.cx = cx; + this.cy = cy; + this.rx = rx; + this.ry = ry; + } + + private void validateShape(@NotNull MeasureContext measureContext) { + float x = cx.resolve(measureContext); + float y = cy.resolve(measureContext); + float rrx = rx.resolve(measureContext); + float rry = ry.resolve(measureContext); + ellipse.setFrame(x - rrx, y - rry, 2 * rrx, 2 * rry); + } + + @Override + public @NotNull Shape shape(@NotNull RenderContext context, boolean validate) { + if (validate) validateShape(context.measureContext()); + return ellipse; + } + + @Override + public @NotNull Rectangle2D bounds(@NotNull RenderContext context, boolean validate) { + if (validate) validateShape(context.measureContext()); + return ellipse.getBounds2D(); + } + + @Override + public double pathLength(@NotNull RenderContext context) { + MeasureContext measureContext = context.measureContext(); + float a = rx.resolve(measureContext); + float b = ry.resolve(measureContext); + if (a == b) return SVGCircle.circumference(a); + return ellipseCircumference(a, b); + } + + @Override + public boolean isClosed(@NotNull RenderContext context) { + return true; + } + + static double ellipseCircumference(double a, double b) { + // This cannot be computed exactly as the circumference is given by an elliptic integral which + // doesn't have a solution in terms of elementary functions. + // The following approximation is due to Hudson + double h = ((a - b) * (a - b)) / ((a + b) * (a + b)); + double h4 = h / 4f; + return 0.25f * Math.PI * (a + b) * (3 * (1 + h4) + (1 / (1f - h4))); + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/SVGLine.java @@ -0,0 +1,85 @@ +/* + * MIT License + * + * Copyright (c) 2021-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.geometry; + +import java.awt.*; +import java.awt.geom.Line2D; +import java.awt.geom.Rectangle2D; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.attributes.value.LengthValue; +import com.github.weisj.jsvg.geometry.util.GeometryUtil; +import com.github.weisj.jsvg.renderer.MeasureContext; +import com.github.weisj.jsvg.renderer.RenderContext; + +public final class SVGLine implements SVGShape { + + private final @NotNull Line2D.Float line = new Line2D.Float(); + private final LengthValue x1; + private final LengthValue y1; + private final LengthValue x2; + private final LengthValue y2; + + public SVGLine(@NotNull LengthValue x1, @NotNull LengthValue y1, @NotNull LengthValue x2, @NotNull LengthValue y2) { + this.x1 = x1; + this.y1 = y1; + this.x2 = x2; + this.y2 = y2; + } + + @Override + public boolean canBeFilled() { + return false; + } + + private void validateShape(@NotNull MeasureContext measureContext) { + line.setLine( + x1.resolve(measureContext), y1.resolve(measureContext), + x2.resolve(measureContext), y2.resolve(measureContext)); + } + + @Override + public @NotNull Shape shape(@NotNull RenderContext context, boolean validate) { + if (validate) validateShape(context.measureContext()); + return line; + } + + @Override + public @NotNull Rectangle2D bounds(@NotNull RenderContext context, boolean validate) { + if (validate) validateShape(context.measureContext()); + return line.getBounds2D(); + } + + @Override + public double pathLength(@NotNull RenderContext context) { + MeasureContext measureContext = context.measureContext(); + return GeometryUtil.lineLength( + x1.resolve(measureContext), y1.resolve(measureContext), + x2.resolve(measureContext), y2.resolve(measureContext)); + } + + @Override + public boolean isClosed(@NotNull RenderContext context) { + return false; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/SVGRectangle.java @@ -0,0 +1,79 @@ +/* + * MIT License + * + * Copyright (c) 2021-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.geometry; + +import java.awt.*; +import java.awt.geom.Rectangle2D; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.attributes.value.LengthValue; +import com.github.weisj.jsvg.renderer.MeasureContext; +import com.github.weisj.jsvg.renderer.RenderContext; + +public final class SVGRectangle implements SVGShape { + + private final @NotNull Rectangle2D.Float rect = new Rectangle2D.Float(); + private final @NotNull LengthValue x; + private final @NotNull LengthValue y; + private final @NotNull LengthValue w; + private final @NotNull LengthValue h; + + public SVGRectangle(@NotNull LengthValue x, @NotNull LengthValue y, @NotNull LengthValue w, + @NotNull LengthValue h) { + this.x = x; + this.y = y; + this.w = w; + this.h = h; + } + + private void validateShape(@NotNull MeasureContext measureContext) { + rect.setRect( + x.resolve(measureContext), + y.resolve(measureContext), + w.resolve(measureContext), + h.resolve(measureContext)); + } + + @Override + public @NotNull Shape shape(@NotNull RenderContext context, boolean validate) { + if (validate) validateShape(context.measureContext()); + return rect; + } + + @Override + public @NotNull Rectangle2D bounds(@NotNull RenderContext context, boolean validate) { + if (validate) validateShape(context.measureContext()); + return rect; + } + + @Override + public double pathLength(@NotNull RenderContext context) { + MeasureContext measureContext = context.measureContext(); + return 2 * (w.resolve(measureContext) + h.resolve(measureContext)); + } + + @Override + public boolean isClosed(@NotNull RenderContext context) { + return true; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/SVGRoundRectangle.java @@ -0,0 +1,96 @@ +/* + * MIT License + * + * Copyright (c) 2021-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.geometry; + +import java.awt.*; +import java.awt.geom.Rectangle2D; +import java.awt.geom.RoundRectangle2D; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.attributes.value.LengthValue; +import com.github.weisj.jsvg.renderer.MeasureContext; +import com.github.weisj.jsvg.renderer.RenderContext; + +public final class SVGRoundRectangle implements SVGShape { + + private final @NotNull RoundRectangle2D.Float rect = new RoundRectangle2D.Float(); + private final @NotNull LengthValue x; + private final @NotNull LengthValue y; + private final @NotNull LengthValue w; + private final @NotNull LengthValue h; + private final @NotNull LengthValue rx; + private final @NotNull LengthValue ry; + + public SVGRoundRectangle(@NotNull LengthValue x, @NotNull LengthValue y, @NotNull LengthValue w, + @NotNull LengthValue h, + @NotNull LengthValue rx, @NotNull LengthValue ry) { + this.x = x; + this.y = y; + this.w = w; + this.h = h; + this.rx = rx; + this.ry = ry; + } + + private void validateShape(@NotNull MeasureContext measureContext) { + rect.setRoundRect( + x.resolve(measureContext), + y.resolve(measureContext), + w.resolve(measureContext), + h.resolve(measureContext), + Math.max(0, rx.resolve(measureContext) * 2), + Math.max(0, ry.resolve(measureContext) * 2)); + } + + @Override + public @NotNull Shape shape(@NotNull RenderContext context, boolean validate) { + if (validate) validateShape(context.measureContext()); + return rect; + } + + @Override + public @NotNull Rectangle2D bounds(@NotNull RenderContext context, boolean validate) { + if (validate) validateShape(context.measureContext()); + return rect.getBounds2D(); + } + + @Override + public double pathLength(@NotNull RenderContext context) { + MeasureContext measureContext = context.measureContext(); + float a = rx.resolve(measureContext); + float b = ry.resolve(measureContext); + double l = 2 * ((w.resolve(measureContext) - 2 * a) + (h.resolve(measureContext) - 2 * b)); + if (a == b) { + // All 4 corners together form a circle + return l + SVGCircle.circumference(a); + } else { + // All 4 corners together form an ellipse + return l + SVGEllipse.ellipseCircumference(a, b); + } + } + + @Override + public boolean isClosed(@NotNull RenderContext context) { + return true; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/SVGShape.java @@ -0,0 +1,54 @@ +/* + * MIT License + * + * Copyright (c) 2021-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.geometry; + +import java.awt.*; +import java.awt.geom.Rectangle2D; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.renderer.RenderContext; + +public interface SVGShape { + + default boolean canBeFilled() { + return true; + } + + default @NotNull Shape shape(@NotNull RenderContext context) { + return shape(context, true); + } + + @NotNull + Shape shape(@NotNull RenderContext context, boolean validate); + + @NotNull + Rectangle2D bounds(@NotNull RenderContext context, boolean validate); + + double pathLength(@NotNull RenderContext context); + + default boolean usesOptimizedBoundsCalculation() { + return true; + } + + boolean isClosed(@NotNull RenderContext context); +} --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/mesh/Bezier.java @@ -0,0 +1,98 @@ +/* + * MIT License + * + * Copyright (c) 2021-2022 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.geometry.mesh; + +import static com.github.weisj.jsvg.geometry.mesh.MeshUtil.p; +import static com.github.weisj.jsvg.geometry.util.GeometryUtil.distanceSquared; +import static com.github.weisj.jsvg.geometry.util.GeometryUtil.midPoint; + +import java.awt.geom.Path2D; +import java.awt.geom.Point2D; + +import org.jetbrains.annotations.NotNull; + +public class Bezier { + public final @NotNull Point2D.Float a; + public final @NotNull Point2D.Float b; + public final @NotNull Point2D.Float c; + public final @NotNull Point2D.Float d; + + public Bezier(@NotNull Point2D.Float a, @NotNull Point2D.Float b, @NotNull Point2D.Float c, + @NotNull Point2D.Float d) { + this.a = a; + this.b = b; + this.c = c; + this.d = d; + } + + public void appendTo(@NotNull Path2D p) { + p.curveTo(b.x, b.y, c.x, c.y, d.x, d.y); + } + + public @NotNull Bezier inverse() { + return new Bezier(d, c, b, a); + } + + public @NotNull Split split() { + Point2D.Float ab = midPoint(a, b); + Point2D.Float bc = midPoint(b, c); + Point2D.Float cd = midPoint(c, d); + Point2D.Float abbc = midPoint(ab, bc); + Point2D.Float bccd = midPoint(bc, cd); + Point2D.Float abbcbccd = midPoint(abbc, bccd); + return new Split<>( + new Bezier(a, ab, abbc, abbcbccd), + new Bezier(abbcbccd, bccd, cd, d)); + } + + public static @NotNull Bezier straightLine(Point2D.Float a, Point2D.Float b) { + return new LineBezier(a, b); + } + + public static @NotNull Bezier combine(@NotNull Bezier b1, @NotNull Bezier b2, @NotNull Bezier b3) { + return new Bezier( + p(b1.a.x + b2.a.x - b3.a.x, b1.a.y + b2.a.y - b3.a.y), + p(b1.b.x + b2.b.x - b3.b.x, b1.b.y + b2.b.y - b3.b.y), + p(b1.c.x + b2.c.x - b3.c.x, b1.c.y + b2.c.y - b3.c.y), + p(b1.d.x + b2.d.x - b3.d.x, b1.d.y + b2.d.y - b3.d.y)); + } + + public int estimateStepCount(float scaleX, float scaleY) { + double steps = Math.max( + Math.max(distanceSquared(a, b, scaleX, scaleY), distanceSquared(c, d, scaleX, scaleY)), + Math.max(distanceSquared(a, c, scaleX, scaleY) / 4, distanceSquared(b, d, scaleX, scaleY) / 4)); + steps *= 18; + steps = Math.max(1, steps); + return (Math.getExponent(steps) + 1) / 2; + } + + + @Override + public String toString() { + return "Bezier{" + + "a=" + a + + ", b=" + b + + ", c=" + c + + ", d=" + d + + '}'; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/mesh/CoonPatch.java @@ -0,0 +1,149 @@ +/* + * MIT License + * + * Copyright (c) 2021-2023 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.geometry.mesh; + +import static com.github.weisj.jsvg.geometry.mesh.MeshUtil.p; +import static com.github.weisj.jsvg.geometry.util.GeometryUtil.midPoint; + +import java.awt.*; +import java.awt.geom.Path2D; +import java.awt.geom.Point2D; + +import org.jetbrains.annotations.NotNull; + +public final class CoonPatch { + public Bezier north; + public Bezier east; + public Bezier south; + public Bezier west; + + public final @NotNull CoonValues coonValues; + + CoonPatch(Bezier north, Bezier east, Bezier south, Bezier west) { + this(north, east, south, west, + new CoonValues(p(0, 0), p(1, 0), p(1, 1), p(0, 1))); + } + + public static @NotNull CoonPatch createUninitialized() { + return new CoonPatch(null, null, null, null); + } + + CoonPatch(Bezier north, Bezier east, Bezier south, Bezier west, @NotNull CoonValues coonValues) { + this.north = north; + this.east = east; + this.south = south; + this.west = west; + this.coonValues = coonValues; + } + + public @NotNull Shape toShape() { + Path2D p = new Path2D.Float(Path2D.WIND_EVEN_ODD); + p.moveTo(north.a.x, north.a.y); + north.appendTo(p); + east.appendTo(p); + south.appendTo(p); + west.appendTo(p); + p.closePath(); + return p; + } + + public Subdivided subdivide() { + Point2D.Float midNorthLinear = midPoint(north.a, north.d); + Point2D.Float midSouthLinear = midPoint(south.d, south.a); + Point2D.Float midWestLinear = midPoint(north.a, south.d); + Point2D.Float midEastLinear = midPoint(north.d, south.a); + + Split northSplit = north.split(); + Split southSplit = south.split(); + Split westSplit = west.split(); + Split eastSplit = east.split(); + + Bezier northLeft = northSplit.left; + Bezier northRight = northSplit.right; + + Bezier southLeft = southSplit.right; + Bezier southRight = southSplit.left; + + @SuppressWarnings({"SuspiciousNameCombination"}) Bezier westBottom = westSplit.left; + @SuppressWarnings({"SuspiciousNameCombination"}) Bezier westTop = westSplit.right; + + @SuppressWarnings({"SuspiciousNameCombination"}) Bezier eastTop = eastSplit.left; + @SuppressWarnings({"SuspiciousNameCombination"}) Bezier eastBottom = eastSplit.right; + + Bezier midNorthSouth = new Bezier( + midPoint(north.a, south.d), + midPoint(north.b, south.c), + midPoint(north.c, south.b), + midPoint(north.d, south.a)); + Bezier midEastWest = new Bezier( + midPoint(east.a, west.d), + midPoint(east.b, west.c), + midPoint(east.c, west.b), + midPoint(east.d, west.a)); + + Split splitNorthSouth = Bezier.combine( + midEastWest, + Bezier.straightLine(northLeft.d, southLeft.a), + Bezier.straightLine(midNorthLinear, midSouthLinear)).split(); + + Split splitWestEast = Bezier.combine( + midNorthSouth, + Bezier.straightLine(westTop.a, eastTop.d), + Bezier.straightLine(midWestLinear, midEastLinear)).split(); + + Point2D.Float midNorthValue = midPoint(coonValues.north, coonValues.east); + Point2D.Float midWestValue = midPoint(coonValues.north, coonValues.west); + Point2D.Float midSouthValue = midPoint(coonValues.west, coonValues.south); + Point2D.Float midEastValue = midPoint(coonValues.east, coonValues.south); + + Point2D.Float gridMidValue = midPoint(midSouthValue, midNorthValue); + CoonValues northWestWeights = new CoonValues(coonValues.north, midNorthValue, gridMidValue, midWestValue); + CoonValues northEastWeights = new CoonValues(midNorthValue, coonValues.east, midEastValue, gridMidValue); + CoonValues southWestWeights = new CoonValues(midWestValue, gridMidValue, midSouthValue, coonValues.west); + CoonValues southEastWeights = new CoonValues(gridMidValue, midEastValue, coonValues.south, midSouthValue); + + CoonPatch northWest = new CoonPatch( + northLeft, splitNorthSouth.left, splitWestEast.left.inverse(), westTop, + northWestWeights); + CoonPatch northEast = new CoonPatch( + northRight, eastTop, splitWestEast.right.inverse(), splitNorthSouth.left.inverse(), + northEastWeights); + CoonPatch southWest = new CoonPatch( + splitWestEast.left, splitNorthSouth.right, southLeft, westBottom, + southWestWeights); + CoonPatch southEast = new CoonPatch( + splitWestEast.right, eastBottom, southRight, splitNorthSouth.right.inverse(), + southEastWeights); + return new Subdivided<>(northWest, northEast, southWest, southEast); + } + + @Override + public String toString() { + return "CoonPatch{" + + "north=" + north + + ", east=" + east + + ", south=" + south + + ", west=" + west + + ", coonValues=" + coonValues + + '}'; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/mesh/CoonValues.java @@ -0,0 +1,48 @@ +/* + * MIT License + * + * Copyright (c) 2021-2023 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.geometry.mesh; + +import java.awt.geom.Point2D; + +public final class CoonValues { + public final Point2D.Float north; + public final Point2D.Float east; + public final Point2D.Float south; + public final Point2D.Float west; + + public CoonValues(Point2D.Float north, Point2D.Float east, Point2D.Float south, Point2D.Float west) { + this.north = north; + this.east = east; + this.south = south; + this.west = west; + } + + @Override + public String toString() { + return "CoonValues{" + + "north=" + north + + ", east=" + east + + ", south=" + south + + ", west=" + west + + '}'; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/mesh/LineBezier.java @@ -0,0 +1,49 @@ +/* + * MIT License + * + * Copyright (c) 2021-2023 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.geometry.mesh; + +import static com.github.weisj.jsvg.geometry.util.GeometryUtil.lerp; + +import java.awt.geom.Path2D; +import java.awt.geom.Point2D; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.geometry.util.GeometryUtil; + +final class LineBezier extends Bezier { + + LineBezier(@NotNull Point2D.Float a, @NotNull Point2D.Float b) { + super(a, lerp(1 / 3f, b, a), lerp(2 / 3f, b, a), b); + } + + @Override + public void appendTo(@NotNull Path2D p) { + p.lineTo(d.x, d.y); + } + + @Override + public @NotNull Split split() { + Point2D.Float mid = GeometryUtil.midPoint(a, d); + return new Split<>(new LineBezier(a, mid), new LineBezier(mid, d)); + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/mesh/MeshUtil.java @@ -0,0 +1,34 @@ +/* + * MIT License + * + * Copyright (c) 2021 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.geometry.mesh; + +import java.awt.geom.Point2D; + +import org.jetbrains.annotations.NotNull; + +final class MeshUtil { + private MeshUtil() {} + + static @NotNull Point2D.Float p(float x, float y) { + return new Point2D.Float(x, y); + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/mesh/Split.java @@ -0,0 +1,34 @@ +/* + * MIT License + * + * Copyright (c) 2021-2023 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.geometry.mesh; + +import org.jetbrains.annotations.NotNull; + +final class Split { + public final @NotNull T left; + public final @NotNull T right; + + public Split(@NotNull T left, @NotNull T right) { + this.left = left; + this.right = right; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/mesh/Subdivided.java @@ -0,0 +1,36 @@ +/* + * MIT License + * + * Copyright (c) 2021-2023 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.geometry.mesh; + +public final class Subdivided { + public final T northWest; + public final T northEast; + public final T southWest; + public final T southEast; + + public Subdivided(T northWest, T northEast, T southWest, T southEast) { + this.northWest = northWest; + this.northEast = northEast; + this.southWest = southWest; + this.southEast = southEast; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/mesh/package-info.java @@ -0,0 +1,3 @@ +@org.osgi.annotation.bundle.Export(attribute = "x-internal") +@aQute.bnd.annotation.jpms.ExportTo("com.github.weisj.jsvg.javafx") +package com.github.weisj.jsvg.geometry.mesh; --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/noise/PerlinTurbulence.java @@ -0,0 +1,258 @@ +/* + * MIT License + * + * Copyright (c) 2021-2023 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.geometry.noise; + +import java.awt.geom.Rectangle2D; + +import org.jetbrains.annotations.Nullable; + +/* + * Results are in the range [1, 2**31 - 2]. + * + * Algorithm is: r = (a * r) mod m where a = 16807 and m = 2**31 - 1 = 2147483647 + * + * See [Park & Miller], CACM vol. 31 no. 10 p. 1195, Oct. 1988 + * + * To test: the algorithm should produce the result 1043618065 as the 10,000th generated number if + * the original seed is 1. + * + * NOTICE: This file contains adapted code from the Batik project: + * https://xmlgraphics.apache.org/batik/ by the Apache Software Foundation. It is licensed under the + * Apache License 2.0 http://www.apache.org/licenses/LICENSE-2.0 + */ +public final class PerlinTurbulence { + private static final int RAND_m = 2147483647; /* 2**31 - 1 */ + private static final int RAND_a = 16807; /* 7**5; primitive root of m */ + private static final int RAND_q = 127773; /* m / a */ + private static final int RAND_r = 2836; /* m % a */ + + private static final int BSize = 0x100; + private static final int BM = 0xff; + private static final double PerlinN = 0x1000; + + private final int[] uLatticeSelector = new int[BSize + 1]; + private final double[] fGradient = new double[(BSize + 1) * 8]; + private final int numOctaves; + private final double xFrequency; + private final double yFrequency; + + public PerlinTurbulence(int seed, int numOctaves, double xFrequency, double yFrequency) { + this.numOctaves = numOctaves; + this.xFrequency = xFrequency; + this.yFrequency = yFrequency; + init(seed); + } + + public static final class StitchInfo { + private int width; + private int height; + private int wrapX; + private int wrapY; + } + + private static int setupSeed(int seed) { + if (seed <= 0) seed = -(seed % (RAND_m - 1)) + 1; + if (seed > RAND_m - 1) seed = RAND_m - 1; + return seed; + } + + private static int random(int seed) { + int result = RAND_a * (seed % RAND_q) - RAND_r * (seed / RAND_q); + if (result <= 0) result += RAND_m; + return result; + } + + private void init(int seed) { + int lSeed = setupSeed(seed); + + int i, j, k; + + for (k = 0; k < 4; k++) { + for (i = 0; i < BSize; i++) { + double u, v; + do { + u = ((lSeed = random(lSeed)) % (BSize + BSize)) - (double) BSize; + v = ((lSeed = random(lSeed)) % (BSize + BSize)) - (double) BSize; + } while (u == 0 && v == 0); + + double s = Math.sqrt(u * u + v * v); + double si = 1 / s; + fGradient[i * 8 + k * 2] = u * si; + fGradient[i * 8 + k * 2 + 1] = v * si; + } + } + + for (i = 0; i < BSize; i++) + uLatticeSelector[i] = i; + + while (--i > 0) { + k = uLatticeSelector[i]; + j = (lSeed = random(lSeed)) % BSize; + uLatticeSelector[i] = uLatticeSelector[j]; + uLatticeSelector[j] = k; + + // Now we apply the lattice to the gradient array, this + // lets us avoid one of the lattice lookups. + int s1 = i << 3; + int s2 = j << 3; + for (j = 0; j < 8; j++) { + double s = fGradient[s1 + j]; + fGradient[s1 + j] = fGradient[s2 + j]; + fGradient[s2 + j] = s; + } + } + uLatticeSelector[BSize] = uLatticeSelector[0]; + for (j = 0; j < 8; j++) + fGradient[(BSize * 8) + j] = fGradient[j]; + } + + private static double curve(double t) { + return t * t * (3. - 2. * t); + } + + private static double lerp(double t, double a, double b) { + return a + t * (b - a); + } + + private void noise2(double[] noiseChannels, double vec0, double vec1, @Nullable StitchInfo stitchInfo) { + double t = vec0 + PerlinN; + int bx0 = (int) t; + int bx1 = bx0 + 1; + final double rx0 = t - bx0; + final double rx1 = rx0 - 1.0f; + final double sx = curve(rx0); + + t = vec1 + PerlinN; + int by0 = (int) t; + int by1 = by0 + 1; + final double ry0 = t - (int) t; + final double ry1 = ry0 - 1.0f; + final double sy = curve(ry0); + + // If stitching, adjust lattice points accordingly. + if (stitchInfo != null) { + if (bx0 >= stitchInfo.wrapX) + bx0 -= stitchInfo.width; + if (bx1 >= stitchInfo.wrapX) + bx1 -= stitchInfo.width; + + if (by0 >= stitchInfo.wrapY) + by0 -= stitchInfo.height; + if (by1 >= stitchInfo.wrapY) + by1 -= stitchInfo.height; + } + + bx0 &= BM; + bx1 &= BM; + by0 &= BM; + by1 &= BM; + + final int i = uLatticeSelector[bx0]; + final int j = uLatticeSelector[bx1]; + + final int b00 = ((i + by0) & BM) << 3; + final int b10 = ((j + by0) & BM) << 3; + final int b01 = ((i + by1) & BM) << 3; + final int b11 = ((j + by1) & BM) << 3; + + for (int channelIndex = 0; channelIndex < noiseChannels.length; channelIndex++) { + int offset = 2 * channelIndex; + noiseChannels[channelIndex] = + lerp(sy, + lerp(sx, + rx0 * fGradient[b00 + offset] + ry0 * fGradient[b00 + offset + 1], + rx1 * fGradient[b10 + offset] + ry0 * fGradient[b10 + offset + 1]), + lerp(sx, + rx0 * fGradient[b01 + offset] + ry1 * fGradient[b01 + offset + 1], + rx1 * fGradient[b11 + offset] + ry1 * fGradient[b11 + offset + 1])); + } + } + + public void turbulence(double[] turbulenceChannels, double pointX, double pointY, + boolean fractalSum, @Nullable StitchInfo stitchInfo, @Nullable Rectangle2D.Double tile) { + double baseFrequencyX = xFrequency; + double baseFrequencyY = yFrequency; + if (stitchInfo != null) { + assert tile != null; + if (baseFrequencyX != 0) { + baseFrequencyX = adjustFrequency(baseFrequencyX, tile.width); + } + if (baseFrequencyY != 0) { + baseFrequencyY = adjustFrequency(baseFrequencyY, tile.height); + } + + stitchInfo.width = (int) (tile.width * baseFrequencyX + 0.5f); + stitchInfo.wrapX = (int) (tile.x * baseFrequencyX + PerlinN + stitchInfo.width); + + stitchInfo.height = (int) (tile.height * baseFrequencyY + 0.5f); + stitchInfo.wrapY = (int) (tile.y * baseFrequencyY + PerlinN + stitchInfo.height); + } + + final double[] fSum = fractalSum + ? new double[] {127.5, 127.5, 127.5, 127.5} + : new double[] {0, 0, 0, 0}; + + double vec0 = pointX * baseFrequencyX; + double vec1 = pointY * baseFrequencyY; + + double ratio = fractalSum ? 127.5 : 255; + + for (int nOctave = 0; nOctave < numOctaves; nOctave++) { + noise2(turbulenceChannels, vec0, vec1, stitchInfo); + if (fractalSum) { + for (int i = 0; i < turbulenceChannels.length; i++) { + fSum[i] += turbulenceChannels[i] * ratio; + } + } else { + for (int i = 0; i < turbulenceChannels.length; i++) { + fSum[i] += Math.abs(turbulenceChannels[i]) * ratio; + } + } + vec0 *= 2; + vec1 *= 2; + ratio *= 0.5; + if (stitchInfo != null) { + // Update stitch values. Subtracting PerlinN before the multiplication and + // adding it afterward simplifies to subtracting it once. + stitchInfo.width *= 2; + stitchInfo.wrapX *= 2; + stitchInfo.wrapX += (int) PerlinN; + + stitchInfo.height *= 2; + stitchInfo.wrapY *= 2; + stitchInfo.wrapY += (int) PerlinN; + } + } + + System.arraycopy(fSum, 0, turbulenceChannels, 0, fSum.length); + } + + private double adjustFrequency(double frequency, double tileSize) { + double fLoFreq = Math.floor(tileSize * frequency) / tileSize; + double fHiFreq = Math.ceil(tileSize * frequency) / tileSize; + if (frequency / fLoFreq < fHiFreq / frequency) { + return fLoFreq; + } else { + return fHiFreq; + } + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/package-info.java @@ -0,0 +1,3 @@ +@org.osgi.annotation.bundle.Export +@aQute.bnd.annotation.jpms.ExportTo("com.github.weisj.jsvg.javafx") +package com.github.weisj.jsvg.geometry; --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/path/Arc.java @@ -0,0 +1,260 @@ +/* + * MIT License + * + * Copyright (c) 2021-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.geometry.path; + +import java.awt.Shape; +import java.awt.geom.AffineTransform; +import java.awt.geom.Arc2D; +import java.awt.geom.Path2D; +import java.awt.geom.Point2D; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.util.ShapeUtil; + +/** + * This is a little used SVG function, as most editors will save curves as + * Béziers. To reduce the need to rely on the Batik library, this functionality + * is being bypassed for the time being. In the future, it would be nice to + * extend the GeneralPath command to include the arcTo ability provided by Batik. + * + * @author Mark McKay + * @author Mark McKay + * @author Jannis Weis + */ +final class Arc extends PathCommand { + + private final float rx; + private final float ry; + private final float xAxisRot; + private final boolean largeArc; + private final boolean sweep; + private final float x; + private final float y; + + public Arc(boolean isRelative, + float rx, float ry, + float xAxisRot, + boolean largeArc, boolean sweep, + float x, float y) { + super(isRelative, 6); + this.rx = rx; + this.ry = ry; + this.xAxisRot = xAxisRot; + this.largeArc = largeArc; + this.sweep = sweep; + this.x = x; + this.y = y; + } + + @Override + public void appendPath(@NotNull Path2D path, @NotNull BuildHistory hist) { + Point2D.Float offset = offset(hist); + + arcTo(path, rx, ry, xAxisRot, largeArc, sweep, + x + offset.x, y + offset.y, + hist.lastPoint.x, hist.lastPoint.y); + hist.setLast(path.getCurrentPoint()); + } + + /** + * Adds an elliptical arc, defined by two radii, an angle from the + * x-axis, a flag to choose the large arc or not, a flag to + * indicate if we increase or decrease the angles and the final + * point of the arc. + * + * @param path The path that the arc will be appended to. + * + * @param rx the x radius of the ellipse + * @param ry the y radius of the ellipse + * + * @param angle the angle from the x-axis of the current + * coordinate system to the x-axis of the ellipse in degrees. + * + * @param largeArcFlag the large arc flag. If true the arc + * spanning less than or equal to 180 degrees is chosen, otherwise + * the arc spanning greater than 180 degrees is chosen + * + * @param sweepFlag the sweep flag. If true the line joining + * center to arc sweeps through decreasing angles otherwise it + * sweeps through increasing angles + * + * @param x the absolute x coordinate of the final point of the arc. + * @param y the absolute y coordinate of the final point of the arc. + * @param x0 - The absolute x coordinate of the initial point of the arc. + * @param y0 - The absolute y coordinate of the initial point of the arc. + */ + private void arcTo(@NotNull Path2D path, float rx, float ry, + float angle, + boolean largeArcFlag, + boolean sweepFlag, + float x, float y, float x0, float y0) { + + // Ensure radii are valid + if (rx == 0 || ry == 0) { + path.lineTo(x, y); + return; + } + + if (x0 == x && y0 == y) { + // If the endpoints (x, y) and (x0, y0) are identical, then this + // is equivalent to omitting the elliptical arc segment entirely. + return; + } + + Arc2D arc = computeRawArc(x0, y0, rx, ry, angle, largeArcFlag, sweepFlag, x, y); + + AffineTransform t = AffineTransform.getRotateInstance( + Math.toRadians(angle), arc.getCenterX(), arc.getCenterY()); + Shape s = ShapeUtil.transformShape(arc, t); + path.append(s, true); + } + + + /** + * This constructs a non-rotated Arc2D from the SVG specification of an + * Elliptical arc. To get the final arc you need to apply a rotation + * transform such as: + *

+ * AffineTransform.getRotateInstance + * (angle, arc.getX()+arc.getWidth()/2, arc.getY()+arc.getHeight()/2); + * + * @param x0 origin of arc in x + * @param y0 origin of arc in y + * @param rx radius of arc in x + * @param ry radius of arc in y + * @param angle number of radians in arc + * @param largeArcFlag the large arc flag + * @param sweepFlag the sweep flag + * @param x ending coordinate of arc in x + * @param y ending coordinate of arc in y + * @return arc shape + * + */ + private static @NotNull Arc2D computeRawArc( + double x0, double y0, + double rx, double ry, + double angle, + boolean largeArcFlag, + boolean sweepFlag, + double x, double y) { + // + // Elliptical arc implementation based on the SVG specification notes + // + + // Compute the half distance between the current and the final point + double dx2 = (x0 - x) / 2.0; + double dy2 = (y0 - y) / 2.0; + // Convert angle from degrees to radians + angle = Math.toRadians(angle % 360.0); + double cosAngle = Math.cos(angle); + double sinAngle = Math.sin(angle); + + // + // Step 1 : Compute (x1, y1) + // + double x1 = cosAngle * dx2 + sinAngle * dy2; + double y1 = -sinAngle * dx2 + cosAngle * dy2; + // Ensure radii are large enough + rx = Math.abs(rx); + ry = Math.abs(ry); + double pRx = rx * rx; + double pRy = ry * ry; + double pX1 = x1 * x1; + double pY1 = y1 * y1; + // check that radii are large enough + double radiiCheck = pX1 / pRx + pY1 / pRy; + if (radiiCheck > 1) { + rx = Math.sqrt(radiiCheck) * rx; + ry = Math.sqrt(radiiCheck) * ry; + pRx = rx * rx; + pRy = ry * ry; + } + + // + // Step 2 : Compute (cx1, cy1) + // + double sign = largeArcFlag == sweepFlag ? -1 : 1; + double sq = ((pRx * pRy) - (pRx * pY1) - (pRy * pX1)) / ((pRx * pY1) + (pRy * pX1)); + sq = sq < 0 ? 0 : sq; + double coefficient = sign * Math.sqrt(sq); + double cx1 = coefficient * ((rx * y1) / ry); + double cy1 = coefficient * -((ry * x1) / rx); + + // + // Step 3 : Compute (cx, cy) from (cx1, cy1) + // + double sx2 = (x0 + x) / 2.0; + double sy2 = (y0 + y) / 2.0; + double cx = sx2 + (cosAngle * cx1 - sinAngle * cy1); + double cy = sy2 + (sinAngle * cx1 + cosAngle * cy1); + + // + // Step 4 : Compute the angleStart (angle1) and the angleExtent (dangle) + // + double ux = (x1 - cx1) / rx; + double uy = (y1 - cy1) / ry; + double vx = (-x1 - cx1) / rx; + double vy = (-y1 - cy1) / ry; + double p; + double n; + // Compute the angle start + n = Math.sqrt((ux * ux) + (uy * uy)); + p = ux; // (1 * ux) + (0 * uy) + sign = (uy < 0) ? -1d : 1d; + double angleStart = Math.toDegrees(sign * Math.acos(p / n)); + + // Compute the angle extent + n = Math.sqrt((ux * ux + uy * uy) * (vx * vx + vy * vy)); + p = ux * vx + uy * vy; + sign = ux * vy - uy * vx < 0 ? -1d : 1d; + double angleExtent = Math.toDegrees(sign * Math.acos(p / n)); + if (!sweepFlag && angleExtent > 0) { + angleExtent -= 360f; + } else if (sweepFlag && angleExtent < 0) { + angleExtent += 360f; + } + angleExtent %= 360f; + angleStart %= 360f; + + // + // We can now build the resulting Arc2D in double precision + // + Arc2D.Double arc = new Arc2D.Double(); + arc.x = cx - rx; + arc.y = cy - ry; + arc.width = rx * 2.0; + arc.height = ry * 2.0; + arc.start = -angleStart; + arc.extent = -angleExtent; + + return arc; + } + + @Override + public String toString() { + return "A " + rx + " " + ry + + " " + xAxisRot + " " + largeArc + + " " + sweep + + " " + x + " " + y; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/path/BezierPathCommand.java @@ -0,0 +1,35 @@ +/* + * MIT License + * + * Copyright (c) 2021-2023 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.geometry.path; + +import java.awt.geom.Point2D; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.geometry.mesh.Bezier; + +@FunctionalInterface +public interface BezierPathCommand { + + @NotNull + Bezier createBezier(@NotNull Point2D.Float start); +} --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/path/BuildHistory.java @@ -0,0 +1,68 @@ +/* + * MIT License + * + * Copyright (c) 2021-2024 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.geometry.path; + +import java.awt.geom.Point2D; + +import org.jetbrains.annotations.NotNull; + +/** + * When building a path from command segments, most need to cache information + * (such as the point finished at) for future commands. This structure allows + * that + * + * @author Mark McKay + * @author Mark McKay + */ +public final class BuildHistory { + + final @NotNull Point2D.Float startPoint = new Point2D.Float(); + final @NotNull Point2D.Float lastPoint = new Point2D.Float(); + final @NotNull Point2D.Float lastCubicKnot = new Point2D.Float(); + final @NotNull Point2D.Float lastQuadraticKnot = new Point2D.Float(); + + public void setStartPoint(@NotNull Point2D point) { + startPoint.setLocation(point); + } + + public void setLast(@NotNull Point2D point) { + lastPoint.setLocation(point); + lastQuadraticKnot.setLocation(point); + lastCubicKnot.setLocation(point); + } + + public void setLastQuadratic(@NotNull Point2D point, float knotX, float knotY) { + setLastQuadratic(point, new Point2D.Float(knotX, knotY)); + } + + public void setLastQuadratic(@NotNull Point2D point, @NotNull Point2D knot) { + lastPoint.setLocation(point); + lastQuadraticKnot.setLocation(knot); + lastCubicKnot.setLocation(point); + } + + public void setLastCubic(@NotNull Point2D current, float x, float y) { + lastPoint.setLocation(current); + lastQuadraticKnot.setLocation(current); + lastCubicKnot.setLocation(x, y); + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/path/Cubic.java @@ -0,0 +1,68 @@ +/* + * MIT License + * + * Copyright (c) 2021-2024 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.geometry.path; + +import java.awt.geom.Path2D; +import java.awt.geom.Point2D; + +import org.jetbrains.annotations.NotNull; + +/** + * @author Mark McKay + * @author Mark McKay + */ +final class Cubic extends PathCommand { + + private final float k1x; + private final float k1y; + private final float k2x; + private final float k2y; + private final float x; + private final float y; + + public Cubic(boolean isRelative, float k1x, float k1y, float k2x, float k2y, float x, float y) { + super(isRelative, 6); + this.k1x = k1x; + this.k1y = k1y; + this.k2x = k2x; + this.k2y = k2y; + this.x = x; + this.y = y; + } + + @Override + public void appendPath(@NotNull Path2D path, @NotNull BuildHistory hist) { + Point2D.Float offset = offset(hist); + + path.curveTo(k1x + offset.x, k1y + offset.y, + k2x + offset.x, k2y + offset.y, + x + offset.x, y + offset.y); + hist.setLastCubic(path.getCurrentPoint(), k2x + offset.x, k2y + offset.y); + } + + @Override + public String toString() { + return "C " + k1x + " " + k1y + + " " + k2x + " " + k2y + + " " + x + " " + y; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/path/CubicBezierCommand.java @@ -0,0 +1,77 @@ +/* + * MIT License + * + * Copyright (c) 2021-2023 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.geometry.path; + +import java.awt.geom.Point2D; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.geometry.mesh.Bezier; + +final class CubicBezierCommand implements BezierPathCommand { + + private final boolean relative; + private final float bx; + private final float by; + private final float cx; + private final float cy; + private final float dx; + private final float dy; + + public CubicBezierCommand(boolean relative, float bx, float by, float cx, float cy, float dx, float dy) { + this.relative = relative; + this.bx = bx; + this.by = by; + this.cx = cx; + this.cy = cy; + this.dx = dx; + this.dy = dy; + } + + @Override + public @NotNull Bezier createBezier(@NotNull Point2D.Float start) { + if (relative) { + return new Bezier(start, + new Point2D.Float(start.x + bx, start.y + by), + new Point2D.Float(start.x + cx, start.y + cy), + new Point2D.Float(start.x + dx, start.y + dy)); + } else { + return new Bezier(start, + new Point2D.Float(bx, by), + new Point2D.Float(cx, cy), + new Point2D.Float(dx, dy)); + } + } + + @Override + public String toString() { + return "CubicBezierCommand{" + + "relative=" + relative + + ", bx=" + bx + + ", by=" + by + + ", cx=" + cx + + ", cy=" + cy + + ", dx=" + dx + + ", dy=" + dy + + '}'; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/path/CubicSmooth.java @@ -0,0 +1,66 @@ +/* + * MIT License + * + * Copyright (c) 2021-2024 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.geometry.path; + +import java.awt.geom.Path2D; +import java.awt.geom.Point2D; + +import org.jetbrains.annotations.NotNull; + +/** + * @author Mark McKay + * @author Mark McKay + * @author Jannis Weis + */ +final class CubicSmooth extends PathCommand { + + private final float x; + private final float y; + private final float k2x; + private final float k2y; + + public CubicSmooth(boolean isRelative, float k2x, float k2y, float x, float y) { + super(isRelative, 6); + this.k2x = k2x; + this.k2y = k2y; + this.x = x; + this.y = y; + } + + @Override + public void appendPath(@NotNull Path2D path, @NotNull BuildHistory hist) { + Point2D.Float offset = offset(hist); + Point2D.Float knot = lastKnotReflectionCubic(hist); + + path.curveTo( + knot.x, knot.y, + k2x + offset.x, k2y + offset.y, + x + offset.x, y + offset.y); + hist.setLastCubic(path.getCurrentPoint(), k2x + offset.x, k2y + offset.y); + } + + @Override + public String toString() { + return "S " + k2x + " " + k2y + + " " + x + " " + y; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/path/Horizontal.java @@ -0,0 +1,56 @@ +/* + * MIT License + * + * Copyright (c) 2021-2024 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.geometry.path; + +import java.awt.geom.Path2D; + +import org.jetbrains.annotations.NotNull; + +/** + * @author Mark McKay + * @author Mark McKay + * @author Jannis Weis + */ +final class Horizontal extends PathCommand { + + private final float x; + + public Horizontal(boolean isRelative, float x) { + super(isRelative, 2); + this.x = x; + } + + @Override + public void appendPath(@NotNull Path2D path, @NotNull BuildHistory hist) { + float xOff = isRelative() ? hist.lastPoint.x : 0f; + float yOff = hist.lastPoint.y; + + path.lineTo(x + xOff, yOff); + hist.setLast(path.getCurrentPoint()); + } + + @Override + public String toString() { + return "H " + x; + } + +} --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/path/LineTo.java @@ -0,0 +1,70 @@ +/* + * MIT License + * + * Copyright (c) 2021-2024 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.geometry.path; + +import java.awt.geom.Path2D; +import java.awt.geom.Point2D; + +import org.jetbrains.annotations.NotNull; + +/** + * @author Mark McKay + * @author Mark McKay + * @author Jannis Weis + */ +final class LineTo extends PathCommand { + + private final float x; + private final float y; + + public LineTo(boolean isRelative, float x, float y) { + super(isRelative, 2); + this.x = x; + this.y = y; + } + + public float x() { + return x; + } + + public float y() { + return y; + } + + @Override + public void appendPath(@NotNull Path2D path, @NotNull BuildHistory hist) { + Point2D.Float offset = offset(hist); + + path.lineTo(x + offset.x, y + offset.y); + hist.setLast(path.getCurrentPoint()); + } + + @Override + public int nodeCount() { + return 2; + } + + @Override + public String toString() { + return "L " + x + " " + y; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/path/LineToBezier.java @@ -0,0 +1,50 @@ +/* + * MIT License + * + * Copyright (c) 2021-2023 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.geometry.path; + +import java.awt.geom.Point2D; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.geometry.mesh.Bezier; + +final class LineToBezier implements BezierPathCommand { + + private final boolean relative; + private final float x; + private final float y; + + public LineToBezier(boolean relative, float x, float y) { + this.relative = relative; + this.x = x; + this.y = y; + } + + @Override + public @NotNull Bezier createBezier(@NotNull Point2D.Float start) { + if (relative) { + return Bezier.straightLine(start, new Point2D.Float(start.x + x, start.y + y)); + } else { + return Bezier.straightLine(start, new Point2D.Float(x, y)); + } + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/path/MoveTo.java @@ -0,0 +1,60 @@ +/* + * MIT License + * + * Copyright (c) 2021-2024 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.geometry.path; + + +import java.awt.geom.Path2D; +import java.awt.geom.Point2D; + +import org.jetbrains.annotations.NotNull; + +/** + * @author Mark McKay + * @author Mark McKay + * @author Jannis Weis + */ +final class MoveTo extends PathCommand { + private final float x; + private final float y; + + public MoveTo(boolean isRelative, float x, float y) { + super(isRelative, 2); + this.x = x; + this.y = y; + } + + @Override + public void appendPath(@NotNull Path2D path, @NotNull BuildHistory hist) { + Point2D.Float offset = offset(hist); + + path.moveTo(x + offset.x, y + offset.y); + hist.setStartPoint(path.getCurrentPoint()); + hist.setLast(path.getCurrentPoint()); + } + + @Override + public String toString() { + return "M " + x + " " + y; + } + + +} --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/path/PathCommand.java @@ -0,0 +1,76 @@ +/* + * MIT License + * + * Copyright (c) 2021-2024 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.geometry.path; + +import java.awt.geom.Path2D; +import java.awt.geom.Point2D; + +import org.jetbrains.annotations.NotNull; + + +public abstract class PathCommand { + + private final boolean isRelative; + private final int nodeCount; + + protected PathCommand(int nodeCount) { + this(false, nodeCount); + } + + protected PathCommand(boolean isRelative, int nodeCount) { + this.isRelative = isRelative; + this.nodeCount = nodeCount; + } + + protected Point2D.Float offset(@NotNull BuildHistory hist) { + if (isRelative()) { + return new Point2D.Float(hist.lastPoint.x, hist.lastPoint.y); + } else { + return new Point2D.Float(0, 0); + } + } + + protected @NotNull Point2D.Float lastKnotReflectionCubic(@NotNull BuildHistory hist) { + return lastKnotReflection(hist.lastPoint, hist.lastCubicKnot); + } + + protected @NotNull Point2D.Float lastKnotReflectionQuadratic(@NotNull BuildHistory hist) { + return lastKnotReflection(hist.lastPoint, hist.lastQuadraticKnot); + } + + private @NotNull Point2D.Float lastKnotReflection(@NotNull Point2D.Float point, @NotNull Point2D.Float knot) { + // Calc knot as reflection of old knot + float kx = point.x * 2f - knot.x; + float ky = point.y * 2f - knot.y; + return new Point2D.Float(kx, ky); + } + + public boolean isRelative() { + return isRelative; + } + + public abstract void appendPath(@NotNull Path2D path, @NotNull BuildHistory hist); + + public int nodeCount() { + return nodeCount; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/path/PathParser.java @@ -0,0 +1,198 @@ +/* + * MIT License + * + * Copyright (c) 2021-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.geometry.path; + +import java.util.ArrayList; +import java.util.List; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.logging.Logger; +import com.github.weisj.jsvg.logging.Logger.Level; +import com.github.weisj.jsvg.logging.impl.LogFactory; +import com.github.weisj.jsvg.util.ParserBase; + +/** + * A helper for parsing {@link PathCommand}s. + * + * @author Jannis Weis + */ +public final class PathParser extends ParserBase { + private static final Logger LOGGER = LogFactory.createLogger(PathParser.class); + private char currentCommand; + + public PathParser(@NotNull String input) { + super(input, 0); + } + + private boolean isCommandChar(char c) { + return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'); + } + + @Override + public float nextFloat() throws NumberFormatException { + float f = super.nextFloat(); + consumeWhiteSpaceOrSeparator(); + return f; + } + + private boolean nextFlag() { + char c = peek(); + consume(); + consumeWhiteSpaceOrSeparator(); + if (c == '1') { + return true; + } else if (c == '0') { + return false; + } else { + throw new IllegalStateException("Invalid flag value '" + c + "' " + currentLocation()); + } + } + + public @NotNull BezierPathCommand parseMeshCommand() { + char peekChar = peek(); + currentCommand = 'z'; + if (isCommandChar(peekChar)) { + consume(); + currentCommand = peekChar; + } + consumeWhiteSpaceOrSeparator(); + switch (currentCommand) { + case 'l': + return new LineToBezier(true, nextFloatOrUnspecified(), nextFloatOrUnspecified()); + case 'L': + return new LineToBezier(false, nextFloatOrUnspecified(), nextFloatOrUnspecified()); + case 'c': + return new CubicBezierCommand(true, nextFloat(), nextFloat(), nextFloat(), nextFloat(), + nextFloatOrUnspecified(), nextFloatOrUnspecified()); + case 'C': + return new CubicBezierCommand(false, nextFloat(), nextFloat(), nextFloat(), nextFloat(), + nextFloatOrUnspecified(), nextFloatOrUnspecified()); + default: + throw new IllegalStateException("Only commands c C l L allowed"); + } + } + + public PathCommand[] parsePathCommand() { + if ("none".equals(input)) return new PathCommand[0]; + List commands = new ArrayList<>(); + try { + parsePathCommandInto(commands); + } catch (Exception e) { + LOGGER.log(Level.INFO, "Error parsing path command: " + e.getMessage()); + } + return commands.toArray(new PathCommand[0]); + } + + private void parsePathCommandInto(List commands) { + currentCommand = 'Z'; + while (hasNext()) { + char peekChar = peek(); + if (isCommandChar(peekChar)) { + consume(); + currentCommand = peekChar; + } + consumeWhiteSpaceOrSeparator(); + + if (currentCommand != 'M' && currentCommand != 'm' && commands.isEmpty()) { + throw new IllegalArgumentException("Path must start with a move command " + currentLocation()); + } + + PathCommand cmd; + switch (currentCommand) { + case 'M': + cmd = new MoveTo(false, nextFloat(), nextFloat()); + currentCommand = 'L'; + break; + case 'm': + cmd = new MoveTo(true, nextFloat(), nextFloat()); + currentCommand = 'l'; + break; + case 'L': + cmd = new LineTo(false, nextFloat(), nextFloat()); + break; + case 'l': + cmd = new LineTo(true, nextFloat(), nextFloat()); + break; + case 'H': + cmd = new Horizontal(false, nextFloat()); + break; + case 'h': + cmd = new Horizontal(true, nextFloat()); + break; + case 'V': + cmd = new Vertical(false, nextFloat()); + break; + case 'v': + cmd = new Vertical(true, nextFloat()); + break; + case 'A': + cmd = new Arc(false, nextFloat(), nextFloat(), nextFloat(), + nextFlag(), nextFlag(), nextFloat(), nextFloat()); + break; + case 'a': + cmd = new Arc(true, nextFloat(), nextFloat(), nextFloat(), + nextFlag(), nextFlag(), nextFloat(), nextFloat()); + break; + case 'Q': + cmd = new Quadratic(false, nextFloat(), nextFloat(), + nextFloat(), nextFloat()); + break; + case 'q': + cmd = new Quadratic(true, nextFloat(), nextFloat(), + nextFloat(), nextFloat()); + break; + case 'T': + cmd = new QuadraticSmooth(false, nextFloat(), nextFloat()); + break; + case 't': + cmd = new QuadraticSmooth(true, nextFloat(), nextFloat()); + break; + case 'C': + cmd = new Cubic(false, nextFloat(), nextFloat(), + nextFloat(), nextFloat(), + nextFloat(), nextFloat()); + break; + case 'c': + cmd = new Cubic(true, nextFloat(), nextFloat(), + nextFloat(), nextFloat(), + nextFloat(), nextFloat()); + break; + case 'S': + cmd = new CubicSmooth(false, nextFloat(), nextFloat(), + nextFloat(), nextFloat()); + break; + case 's': + cmd = new CubicSmooth(true, nextFloat(), nextFloat(), + nextFloat(), nextFloat()); + break; + case 'Z': + case 'z': + cmd = new Terminal(); + break; + default: + throw new IllegalArgumentException("Invalid path element " + currentCommand + currentLocation()); + } + commands.add(cmd); + } + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/path/Quadratic.java @@ -0,0 +1,62 @@ +/* + * MIT License + * + * Copyright (c) 2021-2024 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.geometry.path; + +import java.awt.geom.Path2D; +import java.awt.geom.Point2D; + +import org.jetbrains.annotations.NotNull; + +/** + * @author Mark McKay + * @author Mark McKay + * @author Jannis Weis + */ +final class Quadratic extends PathCommand { + + private final float kx; + private final float ky; + private final float x; + private final float y; + + @Override + public String toString() { + return "Q " + kx + " " + ky + + " " + x + " " + y; + } + + public Quadratic(boolean isRelative, float kx, float ky, float x, float y) { + super(isRelative, 4); + this.kx = kx; + this.ky = ky; + this.x = x; + this.y = y; + } + + @Override + public void appendPath(@NotNull Path2D path, @NotNull BuildHistory hist) { + Point2D.Float offset = offset(hist); + + path.quadTo(kx + offset.x, ky + offset.y, x + offset.x, y + offset.y); + hist.setLastQuadratic(path.getCurrentPoint(), kx + offset.x, ky + offset.y); + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/path/QuadraticSmooth.java @@ -0,0 +1,53 @@ +/* + * MIT License + * + * Copyright (c) 2021-2024 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.geometry.path; + +import java.awt.geom.Path2D; +import java.awt.geom.Point2D; + +import org.jetbrains.annotations.NotNull; + +final class QuadraticSmooth extends PathCommand { + + private final float x; + private final float y; + + public QuadraticSmooth(boolean isRelative, float x, float y) { + super(isRelative, 4); + this.x = x; + this.y = y; + } + + @Override + public void appendPath(@NotNull Path2D path, @NotNull BuildHistory hist) { + Point2D.Float offset = offset(hist); + Point2D.Float knot = lastKnotReflectionQuadratic(hist); + + path.quadTo(knot.x, knot.y, x + offset.x, y + offset.y); + hist.setLastQuadratic(path.getCurrentPoint(), knot); + } + + @Override + public String toString() { + return "T " + x + " " + y; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/path/Terminal.java @@ -0,0 +1,52 @@ +/* + * MIT License + * + * Copyright (c) 2021-2024 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.geometry.path; + +import java.awt.geom.Path2D; + +import org.jetbrains.annotations.NotNull; + +/** + * Finishes a path + * + * @author Mark McKay + * @author Mark McKay + * @author Jannis Weis + */ +public final class Terminal extends PathCommand { + + Terminal() { + super(1); + } + + @Override + public void appendPath(@NotNull Path2D path, @NotNull BuildHistory hist) { + path.closePath(); + hist.setLast(hist.startPoint); + } + + @Override + public String toString() { + return "Z"; + } + +} --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/path/Vertical.java @@ -0,0 +1,55 @@ +/* + * MIT License + * + * Copyright (c) 2021-2024 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.geometry.path; + +import java.awt.geom.Path2D; + +import org.jetbrains.annotations.NotNull; + +/** + * @author Mark McKay + * @author Mark McKay + * @author Jannis Weis + */ +final class Vertical extends PathCommand { + + private final float y; + + public Vertical(boolean isRelative, float y) { + super(isRelative, 2); + this.y = y; + } + + @Override + public void appendPath(@NotNull Path2D path, @NotNull BuildHistory hist) { + float xOff = hist.lastPoint.x; + float yOff = isRelative() ? hist.lastPoint.y : 0f; + + path.lineTo(xOff, y + yOff); + hist.setLast(path.getCurrentPoint()); + } + + @Override + public String toString() { + return "V " + y; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/path/package-info.java @@ -0,0 +1,3 @@ +@org.osgi.annotation.bundle.Export(attribute = "x-internal") +@aQute.bnd.annotation.jpms.ExportTo("com.github.weisj.jsvg.javafx") +package com.github.weisj.jsvg.geometry.path; --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/size/Angle.java @@ -0,0 +1,78 @@ +/* + * MIT License + * + * Copyright (c) 2024 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.geometry.size; + +import java.util.Objects; + +import org.jetbrains.annotations.NotNull; + +public final class Angle { + public static final float UNSPECIFIED_RAW = Float.NaN; + public static final @NotNull Angle UNSPECIFIED = new Angle(AngleUnit.Raw, UNSPECIFIED_RAW); + public static final @NotNull Angle ZERO = new Angle(AngleUnit.Raw, 0); + + private final float radian; + + public Angle(AngleUnit unit, float value) { + this.radian = unit.toRadians(value); + } + + public static boolean isUnspecified(float value) { + return Float.isNaN(value); + } + + public static boolean isSpecified(float value) { + return !isUnspecified(value); + } + + public float radians() { + return radian; + } + + public boolean isUnspecified() { + return isUnspecified(radian); + } + + public boolean isSpecified() { + return !isUnspecified(); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Angle angle = (Angle) o; + return Float.compare(radian, angle.radian) == 0; + } + + @Override + public int hashCode() { + return Objects.hash(radian); + } + + @Override + public String toString() { + return "Angle{" + + "radian=" + radian + + '}'; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/size/AngleUnit.java @@ -0,0 +1,73 @@ +/* + * MIT License + * + * Copyright (c) 2021-2024 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.geometry.size; + +import java.util.Locale; + +import org.jetbrains.annotations.NotNull; + + +public enum AngleUnit { + Deg, + Grad, + Rad, + Turn, + Raw(""); + + private static final AngleUnit[] units = values(); + + private static final double GRADIANS_TO_RADIANS = Math.PI * (2f / 400f); + + public static AngleUnit[] units() { + return units; + } + + private final @NotNull String suffix; + + AngleUnit(@NotNull String suffix) { + this.suffix = suffix; + } + + AngleUnit() { + this.suffix = name().toLowerCase(Locale.ENGLISH); + } + + public @NotNull String suffix() { + return suffix; + } + + public float toRadians(float value) { + switch (this) { + case Raw: + case Deg: + return (float) Math.toRadians(value); + case Grad: + return (float) (value * GRADIANS_TO_RADIANS); + case Rad: + return value; + case Turn: + return (float) (value * Math.PI * 2f); + default: + throw new IllegalArgumentException("Unknown angle unit " + this); + } + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/size/FloatInsets.java @@ -0,0 +1,79 @@ +/* + * MIT License + * + * Copyright (c) 2023 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.geometry.size; + +import java.util.Objects; + +public final class FloatInsets { + private final float top; + private final float left; + private final float bottom; + private final float right; + + public FloatInsets(float top, float left, float bottom, float right) { + this.top = top; + this.left = left; + this.bottom = bottom; + this.right = right; + } + + public FloatInsets() { + this(0, 0, 0, 0); + } + + public float top() { + return top; + } + + public float bottom() { + return bottom; + } + + public float left() { + return left; + } + + public float right() { + return right; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof FloatInsets)) return false; + FloatInsets that = (FloatInsets) o; + return Float.compare(that.top, top) == 0 + && Float.compare(that.bottom, bottom) == 0 + && Float.compare(that.left, left) == 0 + && Float.compare(that.right, right) == 0; + } + + @Override + public int hashCode() { + return Objects.hash(top, left, bottom, right); + } + + @Override + public String toString() { + return "[" + top + "," + left + "," + bottom + "," + right + "]"; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/size/Length.java @@ -0,0 +1,248 @@ +/* + * MIT License + * + * Copyright (c) 2021-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.geometry.size; + +import java.util.Objects; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.attributes.UnitType; +import com.github.weisj.jsvg.attributes.value.LengthValue; +import com.github.weisj.jsvg.attributes.value.PercentageDimension; +import com.github.weisj.jsvg.renderer.MeasureContext; + +public final class Length implements LengthValue { + public static final float UNSPECIFIED_RAW = Float.NaN; + public static final @NotNull Length UNSPECIFIED = new Length(Unit.RAW, UNSPECIFIED_RAW); + public static final @NotNull Length ZERO = new Length(Unit.RAW, 0); + public static final @NotNull Length ONE = new Length(Unit.RAW, 1); + public static final @NotNull Length INHERITED = new Length(Unit.RAW, 0); + + private final @NotNull Unit unit; + private final float value; + + private static final float PIXELS_PER_INCH = 96f; + private static final float INCHES_PER_CM = .3936f; + + + public Length(@NotNull Unit unit, float value) { + this.unit = unit; + this.value = value; + } + + public Length(@NotNull Length ry) { + this.unit = ry.unit; + this.value = ry.value; + } + + public static boolean isUnspecified(float value) { + return Float.isNaN(value); + } + + public static boolean isSpecified(float value) { + return !isUnspecified(value); + } + + private static float resolveNonPercentage(@NotNull MeasureContext context, Unit unit, float value) { + if (unit == Unit.RAW) { + // If we are unspecified this will return UNSPECIFIED_RAW as intended. + return value; + } + assert !unit.isPercentage(); + switch (unit) { + case PX: + return value; + case IN: + return PIXELS_PER_INCH * value; + case CM: + return INCHES_PER_CM * PIXELS_PER_INCH * value; + case MM: + return 0.1f * INCHES_PER_CM * PIXELS_PER_INCH * value; + case Q: + return 0.025f * INCHES_PER_CM * PIXELS_PER_INCH * value; + case PT: + return (1f / 72f) * PIXELS_PER_INCH * value; + case PC: + return (1f / 6f) * PIXELS_PER_INCH * value; + case EM: + return context.em() * value; + case REM: + return context.rem() * value; + case CH: + case EX: + return context.ex() * value; + default: + throw new UnsupportedOperationException("Not implemented: Can't convert " + unit + " to pixel"); + } + } + + @Override + public float resolve(@NotNull MeasureContext context) { + float raw = raw(); + switch (unit) { + case PERCENTAGE_LENGTH: + return (raw * context.normedDiagonalLength()) / 100f; + case VW: + case VI: + case PERCENTAGE_WIDTH: + return (raw * context.viewWidth()) / 100f; + case VH: + case VB: + case PERCENTAGE_HEIGHT: + return (raw * context.viewHeight()) / 100f; + case PERCENTAGE: + return raw / 100f; + case V_MIN: + return (raw * Math.min(context.viewWidth(), context.viewHeight())) / 100f; + case V_MAX: + return (raw * Math.max(context.viewWidth(), context.viewHeight())) / 100f; + default: + return resolveNonPercentage(context, unit, raw); + } + } + + /** + * Used for resolving font sizes. Relative values will be resolves with respect to the current font size. + * This isn't dependent on the current viewBox. + * @param context the measuring context. + * @return the resolved size. + */ + public float resolveFontSize(@NotNull MeasureContext context) { + float raw = raw(); + switch (unit) { + case PERCENTAGE_LENGTH: + case PERCENTAGE_WIDTH: + case PERCENTAGE_HEIGHT: + throw new IllegalStateException("Can't resolve font size with geometric percentage unit"); + case PERCENTAGE: + return (raw / 100f) * context.em(); + default: + return resolveNonPercentage(context, unit, raw); + } + } + + @Override + public @NotNull String toString() { + if (isUnspecified()) return ""; + return value + unit.suffix(); + } + + public boolean isZero() { + return value == 0; + } + + @Override + public boolean isConstantlyZero() { + return isZero(); + } + + @Override + public boolean isConstantlyNonNegative() { + return raw() >= 0; + } + + public boolean isAbsolute() { + switch (unit) { + case RAW: + case PX: + case IN: + case CM: + case MM: + case Q: + case PT: + case PC: + return true; + default: + return false; + } + } + + public float raw() { + return value; + } + + public @NotNull Unit unit() { + return unit; + } + + public boolean isUnspecified() { + return isUnspecified(value); + } + + public boolean isSpecified() { + return isSpecified(value); + } + + public @NotNull Length coerceNonNegative() { + if (isSpecified() && value <= 0) return ZERO; + return this; + } + + public @NotNull Length coercePercentageToCorrectUnit(@NotNull UnitType unitType, + @NotNull PercentageDimension dimension) { + if (unitType == UnitType.UserSpaceOnUse) return this; + if (unit.isPercentage()) return this; + Unit u; + switch (dimension) { + case WIDTH: + u = Unit.PERCENTAGE_WIDTH; + break; + case HEIGHT: + u = Unit.PERCENTAGE_HEIGHT; + break; + case LENGTH: + u = Unit.PERCENTAGE_LENGTH; + break; + case CUSTOM: + u = Unit.PERCENTAGE; + break; + default: + throw new IllegalStateException("Can't coerce to percentage with no dimension"); + } + return new Length(u, raw() * 100); + } + + public @NotNull Length orElseIfUnspecified(float value) { + if (isUnspecified()) return Unit.RAW.valueOf(value); + return this; + } + + public @NotNull Length multiply(float scalingFactor) { + if (scalingFactor == 0) return ZERO; + if (scalingFactor == 1) return this; + return new Length(unit, scalingFactor * value); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof Length)) return false; + Length length = (Length) o; + return unit == length.unit && Float.compare(length.value, value) == 0; + } + + @Override + public int hashCode() { + return Objects.hash(unit, value); + } + +} --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/size/Percentage.java @@ -0,0 +1,110 @@ +/* + * MIT License + * + * Copyright (c) 2024-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.geometry.size; + +import java.util.Objects; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.attributes.value.PercentageValue; +import com.github.weisj.jsvg.renderer.MeasureContext; +import com.google.errorprone.annotations.Immutable; + +@Immutable +public final class Percentage implements Comparable, PercentageValue { + public static final float UNSPECIFIED_RAW = Float.NaN; + public static final @NotNull Percentage UNSPECIFIED = new Percentage(UNSPECIFIED_RAW); + public static final @NotNull Percentage ZERO = new Percentage(0); + public static final @NotNull Percentage ONE = new Percentage(1); + public static final @NotNull Percentage INHERITED = new Percentage(1); + + private final float value; + + public Percentage(float value) { + this.value = value; + } + + public static boolean isUnspecified(float value) { + return Float.isNaN(value); + } + + public static boolean isSpecified(float value) { + return !isUnspecified(value); + } + + public float value() { + return value; + } + + @Override + public float get(@NotNull MeasureContext context) { + return value; + } + + @Override + public @NotNull PercentageValue multiply(@NotNull PercentageValue other) { + if (this.value == 1) return other; + if (other instanceof Percentage) { + float otherValue = ((Percentage) other).value; + if (otherValue == 0 || this.value == 0) return ZERO; + if (otherValue == 1) return this; + return new Percentage(this.value * otherValue); + } + return other.multiply(this); + } + + public boolean isUnspecified() { + return isUnspecified(value); + } + + public boolean isSpecified() { + return !isUnspecified(); + } + + public @NotNull Percentage orElseIfUnspecified(float value) { + if (isUnspecified()) return new Percentage(value); + return this; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Percentage percentage = (Percentage) o; + return Float.compare(value, percentage.value) == 0; + } + + @Override + public int hashCode() { + return Objects.hash(value); + } + + @Override + public String toString() { + return (value * 100) + "%"; + } + + @Override + public int compareTo(@NotNull Percentage o) { + return Float.compare(value, o.value); + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/size/Unit.java @@ -0,0 +1,93 @@ +/* + * MIT License + * + * Copyright (c) 2021-2024 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.geometry.size; + +import java.util.Locale; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.attributes.SuffixUnit; + +public enum Unit implements SuffixUnit { + PX, + CM, + Q, + MM, + IN, + EM, + REM, + EX, + CH, + PT, + PC, + VW, + VH, + VI, + VB, + V_MIN("vmin"), + V_MAX("vmax"), + PERCENTAGE("%"), + PERCENTAGE_LENGTH("%"), + PERCENTAGE_WIDTH("%"), + PERCENTAGE_HEIGHT("%"), + RAW(""); + + private static final Unit[] units = values(); + + @Override + public @NotNull Unit @NotNull [] units() { + return units; + } + + private final @NotNull String suffix; + + Unit(@NotNull String suffix) { + this.suffix = suffix; + } + + Unit() { + this.suffix = name().toLowerCase(Locale.ENGLISH); + } + + @Override + public @NotNull Length valueOf(float value) { + if (value == 0) return Length.ZERO; + return new Length(this, value); + } + + @Override + public @NotNull String suffix() { + return suffix; + } + + public boolean isPercentage() { + switch (this) { + case PERCENTAGE: + case PERCENTAGE_LENGTH: + case PERCENTAGE_WIDTH: + case PERCENTAGE_HEIGHT: + return true; + default: + return false; + } + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/size/package-info.java @@ -0,0 +1,3 @@ +@org.osgi.annotation.bundle.Export(attribute = "x-internal") +@aQute.bnd.annotation.jpms.ExportTo("com.github.weisj.jsvg.javafx") +package com.github.weisj.jsvg.geometry.size; --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/util/GeometryUtil.java @@ -0,0 +1,333 @@ +/* + * MIT License + * + * Copyright (c) 2021-2026 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.geometry.util; + +import java.awt.*; +import java.awt.geom.*; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import com.github.weisj.jsvg.attributes.value.TransformValue; +import com.github.weisj.jsvg.geometry.size.FloatInsets; +import com.github.weisj.jsvg.renderer.RenderContext; + +public final class GeometryUtil { + private static final float EPS = 0.0001f; + + private GeometryUtil() {} + + public static boolean approximatelyEqual(double a, double b) { + return Math.abs(a - b) < EPS; + } + + public static boolean approximatelyZero(double a) { + return approximatelyEqual(a, 0); + } + + public static boolean notablyGreater(double a, double b) { + return a - b > EPS; + } + + public static boolean approximatelyNegative(double a) { + return a < EPS; + } + + public static boolean approximatelyPositive(double a) { + return a > -EPS; + } + + public static double scaleXOfTransform(@Nullable AffineTransform at) { + if (at == null) return 1; + double sx = at.getScaleX(); + double shy = at.getShearY(); + return Math.sqrt(sx * sx + shy * shy); + } + + public static double scaleYOfTransform(@Nullable AffineTransform at) { + if (at == null) return 1; + double sy = at.getScaleY(); + double shx = at.getShearX(); + return Math.sqrt(sy * sy + shx * shx); + } + + public static @NotNull Point2D.Float midPoint(@NotNull Point2D.Float x, @NotNull Point2D.Float y) { + return new Point2D.Float((x.x + y.x) / 2, (x.y + y.y) / 2); + } + + public static @NotNull Point2D.Float lerp(float t, @NotNull Point2D.Float a, @NotNull Point2D.Float b) { + return new Point2D.Float(lerp(t, b.x, a.x), lerp(t, b.y, a.y)); + } + + public static float lerp(float t, float a, float b) { + return (1 - t) * a + t * b; + } + + public static double lerp(float t, double a, double b) { + return (1 - t) * a + t * b; + } + + public static double distanceSquared(@NotNull Point2D.Float p1, @NotNull Point2D.Float p2, float scaleX, + float scaleY) { + return distanceSquared(scaleX * p1.x, scaleY * p1.y, scaleX * p2.x, scaleY * p2.y); + } + + public static double distanceSquared(@NotNull Point2D.Float p1, @NotNull Point2D.Float p2) { + return distanceSquared(p1.x, p1.y, p2.x, p2.y); + } + + public static double distanceSquared(double x1, double y1, double x2, double y2) { + double dx = x2 - x1; + double dy = y2 - y1; + return dx * dx + dy * dy; + } + + public static double pathLength(@NotNull Shape shape) { + return pathLength(shape.getPathIterator(null)); + } + + private static double pathLength(@NotNull PathIterator pathIterator) { + PathLengthCalculator pathLengthCalculator = new PathLengthCalculator(); + double length = 0; + double[] args = new double[6]; + while (!pathIterator.isDone()) { + length += pathLengthCalculator.segmentLength(pathIterator.currentSegment(args), args); + pathIterator.next(); + } + return length; + } + + public static boolean isSingleClosedPath(@NotNull Shape shape) { + PathIterator pathIterator = shape.getPathIterator(null); + int numPaths = 0; + int numClosedPaths = 0; + float[] segment = new float[6]; + while (!pathIterator.isDone()) { + switch (pathIterator.currentSegment(segment)) { + case PathIterator.SEG_MOVETO: + numPaths++; + break; + case PathIterator.SEG_CLOSE: + numClosedPaths++; + break; + default: + break; + } + if (numPaths > 1 || numClosedPaths > 1) return false; + pathIterator.next(); + } + return numPaths == 1 && numClosedPaths == 1; + } + + public static double lineLength(double x1, double y1, double x2, double y2) { + return Math.sqrt(GeometryUtil.distanceSquared(x1, y1, x2, y2)); + } + + public static @NotNull Rectangle2D containingBoundsAfterTransform(@NotNull AffineTransform transform, + @NotNull Rectangle2D rect) { + if (transform.isIdentity()) return rect.getBounds2D(); + Point2D.Double p1 = new Point2D.Double(rect.getX(), rect.getY()); + Point2D.Double p2 = new Point2D.Double(rect.getX() + rect.getWidth(), rect.getY()); + Point2D.Double p3 = new Point2D.Double(rect.getX(), rect.getY() + rect.getHeight()); + Point2D.Double p4 = new Point2D.Double(rect.getX() + rect.getWidth(), rect.getY() + rect.getHeight()); + Rectangle2D r1 = rect.getBounds2D(); + r1.setFrameFromDiagonal(transform.transform(p1, p1), transform.transform(p2, p2)); + Rectangle2D r2 = rect.getBounds2D(); + r2.setFrameFromDiagonal(transform.transform(p3, p3), transform.transform(p4, p4)); + Rectangle2D.union(r1, r2, r1); + return r1; + } + + public static float left(@NotNull Rectangle2D rect) { + return (float) rect.getX(); + } + + public static float top(@NotNull Rectangle2D rect) { + return (float) rect.getY(); + } + + public static float right(@NotNull Rectangle2D rect) { + return (float) (rect.getX() + rect.getWidth()); + } + + public static float bottom(@NotNull Rectangle2D rect) { + return (float) (rect.getY() + rect.getHeight()); + } + + public static @NotNull Rectangle2D grow(@NotNull Rectangle2D bounds, FloatInsets grow) { + return new Rectangle2D.Double( + bounds.getX() - grow.left(), + bounds.getY() - grow.top(), + bounds.getWidth() + grow.left() + grow.right(), + bounds.getHeight() + grow.top() + grow.bottom()); + } + + public static @NotNull Rectangle2D grow(@NotNull Rectangle2D bounds, double increase) { + return new Rectangle2D.Double( + bounds.getX() - increase, + bounds.getY() - increase, + bounds.getWidth() + 2 * increase, + bounds.getHeight() + 2 * increase); + } + + public static @NotNull FloatInsets max(@NotNull FloatInsets in1, @NotNull FloatInsets in2) { + return new FloatInsets( + Math.max(in1.top(), in2.top()), + Math.max(in1.left(), in2.left()), + Math.max(in1.bottom(), in2.bottom()), + Math.max(in1.right(), in2.right())); + } + + public static @NotNull FloatInsets min(@NotNull FloatInsets in1, @NotNull FloatInsets in2) { + return new FloatInsets( + Math.min(in1.top(), in2.top()), + Math.min(in1.left(), in2.left()), + Math.min(in1.bottom(), in2.bottom()), + Math.min(in1.right(), in2.right())); + } + + public static @NotNull FloatInsets overhangInsets(@NotNull Rectangle2D reference, @NotNull Rectangle2D bounds) { + return new FloatInsets( + Math.max(0, top(reference) - top(bounds)), + Math.max(0, left(reference) - left(bounds)), + Math.max(0, bottom(bounds) - bottom(reference)), + Math.max(0, right(bounds) - right(reference))); + } + + public static @NotNull String compactRepresentation(@NotNull Rectangle2D rect) { + return "[" + rect.getX() + ", " + rect.getY() + ", " + rect.getWidth() + "x" + rect.getHeight() + "]"; + } + + public static @NotNull Rectangle2D toIntegerBounds(@NotNull Rectangle2D in, @NotNull Rectangle2D out) { + double minY = Math.floor(in.getMinY()); + double minX = Math.floor(in.getMinX()); + double maxX = Math.ceil(in.getMaxX()); + double maxY = Math.ceil(in.getMaxY()); + out.setFrame(minX, minY, maxX - minX, maxY - minY); + return out; + } + + public static @NotNull Rectangle2D adjustForAliasing(@NotNull Rectangle2D r) { + return toIntegerBounds(r, r); + } + + public static @NotNull AffineTransform createInverse(@NotNull AffineTransform at) { + try { + return at.createInverse(); + } catch (NoninvertibleTransformException e) { + throw new IllegalStateException(e); + } + } + + public static @Nullable AffineTransform toAwtTransform(@NotNull RenderContext context, + @Nullable TransformValue transform) { + if (transform == null) return null; + return transform.get(context.measureContext()); + } + + public static @NotNull Point2D lastPointOnPath(@NotNull PathIterator pathIterator) { + Point2D lastPoint = new Point2D.Double(); + Point2D lastMoveToPoint = new Point2D.Double(); + double[] args = new double[6]; + while (!pathIterator.isDone()) { + switch (pathIterator.currentSegment(args)) { + case PathIterator.SEG_MOVETO: + lastPoint.setLocation(args[0], args[1]); + lastMoveToPoint.setLocation(args[0], args[1]); + break; + case PathIterator.SEG_LINETO: + lastPoint.setLocation(args[0], args[1]); + break; + case PathIterator.SEG_QUADTO: + lastPoint.setLocation(args[2], args[3]); + break; + case PathIterator.SEG_CUBICTO: + lastPoint.setLocation(args[4], args[5]); + break; + case PathIterator.SEG_CLOSE: + lastPoint.setLocation(lastMoveToPoint.getX(), lastMoveToPoint.getY()); + break; + default: + break; + } + pathIterator.next(); + } + return lastPoint; + } + + public enum Space { + USER, + ROOT, + DEVICE + } + + public static @NotNull Rectangle2D convertBounds(@NotNull RenderContext context, @NotNull Rectangle2D r, + @NotNull Space from, @NotNull Space to) { + if (from == to) return r; + Rectangle2D out = r; + if (from == Space.USER) { + if (to == Space.ROOT) { + out = containingBoundsAfterTransform(context.userSpaceTransform(), r); + } else if (to == Space.DEVICE) { + out = containingBoundsAfterTransform(context.userSpaceTransform(), r); + out = containingBoundsAfterTransform(context.rootTransform(), out); + } + } + if (from == Space.ROOT) { + if (to == Space.USER) { + out = containingBoundsAfterTransform(createInverse(context.rootTransform()), r); + } else if (to == Space.DEVICE) { + out = containingBoundsAfterTransform(context.rootTransform(), r); + } + } + if (from == Space.DEVICE) { + if (to == Space.USER) { + out = containingBoundsAfterTransform(createInverse(context.rootTransform()), r); + out = containingBoundsAfterTransform(createInverse(context.userSpaceTransform()), out); + } else if (to == Space.ROOT) { + out = containingBoundsAfterTransform(createInverse(context.rootTransform()), r); + } + } + return out; + } + + public static @NotNull Rectangle2D userBoundsToDeviceBounds(@NotNull RenderContext context, + @NotNull Rectangle2D r) { + return convertBounds(context, r, Space.USER, Space.DEVICE); + } + + public static @NotNull Point2D getLocation(@NotNull Rectangle2D r) { + return new Point2D.Double(r.getX(), r.getY()); + } + + public static boolean isValidRect(@NotNull Rectangle2D r) { + return !Double.isNaN(r.getX()) + && !Double.isNaN(r.getY()) + && !Double.isNaN(r.getWidth()) + && !Double.isNaN(r.getHeight()); + } + + public static @NotNull AffineTransform interpolate(@NotNull AffineTransform a, @NotNull AffineTransform b, + float t) { + return TransformUtil.interpolate(a, b, t); + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/util/PathLengthCalculator.java @@ -0,0 +1,173 @@ +/* + * MIT License + * + * Copyright (c) 2022-2026 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.geometry.util; + + +import java.awt.geom.PathIterator; + + +public final class PathLengthCalculator { + + private double x = 0; + private double y = 0; + private double xStart = x; + private double yStart = y; + + public double segmentLength(int segmentType, double[] coords) { + double segmentLength = 0; + switch (segmentType) { + case PathIterator.SEG_MOVETO: + x = coords[0]; + y = coords[1]; + xStart = x; + yStart = y; + break; + case PathIterator.SEG_LINETO: + segmentLength = lineLength(x, y, coords[0], coords[1]); + x = coords[0]; + y = coords[1]; + break; + case PathIterator.SEG_QUADTO: + segmentLength = quadraticParametricLength(x, y, coords[0], coords[1], coords[2], coords[3]); + x = coords[2]; + y = coords[3]; + break; + case PathIterator.SEG_CUBICTO: + segmentLength = + cubicParametricLength(x, y, coords[0], coords[1], coords[2], coords[3], coords[4], coords[5]); + x = coords[4]; + y = coords[5]; + break; + case PathIterator.SEG_CLOSE: + segmentLength = lineLength(x, y, xStart, yStart); + x = xStart; + y = yStart; + break; + default: + throw new IllegalStateException(); + } + return segmentLength; + } + + + private double lineLength(double x1, double y1, double x2, double y2) { + return GeometryUtil.lineLength(x1, y1, x2, y2); + } + + /* + * Takes the start-, control- and end-point coordinates. + * + * Integral calculation by Dave Eberly, slightly modified for the edge case with collinear control + * point. + * + * See: http://www.gamedev.net/topic/551455-length-of-a-generalized-quadratic-bezier-curve-in-3d/ + */ + private double quadraticParametricLength(double ax, double ay, double bx, double by, double cx, double cy) { + // A == C + if (ax == cx && ay == cy) { + // A == B + if (ax == bx && ay == by) return 0; + return lineLength(ax, ay, bx, by); + } + // A == B || C == B + if ((ax == bx && ay == by) + || (cx == bx && cy == by)) { + return lineLength(ax, ay, cx, cy); + } + double ax0 = bx - ax; + double ay0 = by - ay; + + double ax1 = ax - 2 * bx + cx; + double ay1 = ay - 2 * by + cy; + + if (ax1 != 0 || ay1 != 0) { + double c = 4f * dot2D(ax1, ay1, ax1, ay1); + double b = 8f * dot2D(ax0, ay0, ax1, ay1); + double a = 4f * dot2D(ax0, ay0, ax0, ay0); + double q = 4f * a * c - b * b; + double twoCpB = 2.0 * c + b; + double sumCBA = c + b + a; + double l0 = (0.25 / c) * (twoCpB * Math.sqrt(sumCBA) - b * Math.sqrt(a)); + if (q == 0.0) return l0; + double l1 = (q / (8.0 * Math.pow(c, 1.5))) + * (Math.log(2.0 * Math.sqrt(c * sumCBA) + twoCpB) - Math.log(2.0 * Math.sqrt(c * a) + b)); + return l0 + l1; + } else { + return 2f * lineLength(0, 0, ax0, ay0); + } + } + + private double dot2D(double x1, double y1, double x2, double y2) { + return x1 * x2 + y1 * y2; + } + + + /* + * Arc-length calculation for a cubic Bézier curve using 12-point Gauss-Legendre quadrature. + * + * P'(t) = 3[(B-A)(1-t)² + 2(C-B)(1-t)t + (D-C)t²] + * + * Nodes and weights taken from standard Gauss-Legendre tables (interval [-1,1], mapped to [0,1]). + * + * Note: Exact calculation as for the quadratic case isn't possible due to the integral not being + * solvable with elementary functions. + */ + private double cubicParametricLength(double ax, double ay, double bx, double by, double cx, double cy, + double dx, double dy) { + // 12-point Gauss-Legendre nodes on [-1,1] + final double[] nodes = { + -0.9815606342467192, -0.9041172563704749, -0.7699026741943047, + -0.5873179542866175, -0.3678314989981802, -0.1252334085114689, + 0.1252334085114689, 0.3678314989981802, 0.5873179542866175, + 0.7699026741943047, 0.9041172563704749, 0.9815606342467192 + }; + // Corresponding weights + final double[] weights = { + 0.0471753363865118, 0.1069393259953184, 0.1600783285433462, + 0.2031674267230659, 0.2334925365383548, 0.2491470458134028, + 0.2491470458134028, 0.2334925365383548, 0.2031674267230659, + 0.1600783285433462, 0.1069393259953184, 0.0471753363865118 + }; + + // Derivative coefficients: P'(t) = 3[A1*(1-t)^2 + 2*A2*(1-t)*t + A3*t^2] + // where A1 = B-A, A2 = C-B, A3 = D-C + double a1x = bx - ax; + double a1y = by - ay; + double a2x = cx - bx; + double a2y = cy - by; + double a3x = dx - cx; + double a3y = dy - cy; + + double sum = 0; + for (int i = 0; i < nodes.length; i++) { + // Map node from [-1,1] to [0,1]: t = (node + 1) / 2 + double t = (nodes[i] + 1.0) * 0.5; + double mt = 1.0 - t; + // Derivative / 3 + double dtx = a1x * mt * mt + 2.0 * a2x * mt * t + a3x * t * t; + double dty = a1y * mt * mt + 2.0 * a2y * mt * t + a3y * t * t; + sum += weights[i] * Math.sqrt(dtx * dtx + dty * dty); + } + // Factor of 3 from derivative, factor of 0.5 from interval mapping [-1,1] -> [0,1] + return 3.0 * 0.5 * sum; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/util/ReversePathIterator.java @@ -0,0 +1,255 @@ +/* + * MIT License + * + * Copyright (c) 2021-2023 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.geometry.util; + +import java.awt.geom.IllegalPathStateException; +import java.awt.geom.PathIterator; + +/** + * A path iterator which iterates over a path in the reverse direction. + * This is missing in the java.awt.geom package, although it's quite simple to implement. + * After initialization the original PathIterator is not used any longer. + *

+ * + * @author Rammi + * @version $Revision: 1.3 $ + */ +public final class ReversePathIterator implements PathIterator { + /** The winding rule. */ + private final int windingRule; + /** The reversed coordinates. */ + private final double[] coordinates; + /** The reversed segment types. */ + private final int[] segmentTypes; + /** The index into the coordinates during iteration. */ + private int coordIndex = 0; + /** The index into the segment types during iteration. */ + private int segmentIndex = 0; + + /** + * Create an inverted path iterator from a standard one, keeping the winding rule. + * @param original original iterator + */ + public ReversePathIterator(PathIterator original) { + this(original, original.getWindingRule()); + } + + /** + * Create an inverted path iterator from a standard one. + * @param original original iterator + * @param windingRule winding rule of newly created iterator + */ + public ReversePathIterator(PathIterator original, int windingRule) { + this.windingRule = windingRule; + + double[] coords = new double[16]; + int coordPos = 0; + int[] segTypes = new int[8]; + int segPos = 0; + boolean first = true; + + double[] temp = new double[6]; + while (!original.isDone()) { + if (segPos == segTypes.length) { + // resize + int[] dummy = new int[2 * segPos]; + System.arraycopy(segTypes, 0, dummy, 0, segPos); + segTypes = dummy; + } + final int segType = segTypes[segPos++] = original.currentSegment(temp); + if (first) { + if (segType != SEG_MOVETO) { + throw new IllegalPathStateException("missing initial moveto in path definition"); + } + first = false; + } + final int copy = coordinatesForSegmentType(segType); + if (copy > 0) { + if (coordPos + copy > coords.length) { + // resize + double[] dummy = new double[coords.length * 2]; + System.arraycopy(coords, 0, dummy, 0, coords.length); + coords = dummy; + } + for (int c = 0; c < copy; ++c) { + coords[coordPos++] = temp[c]; + } + } + original.next(); + } + + // === reverse everything === + // --- reverse coordinates --- + coordinates = new double[coordPos]; + for (int p = coordPos / 2 - 1; p >= 0; --p) { + coordinates[2 * p] = coords[coordPos - 2 * p - 2]; + coordinates[2 * p + 1] = coords[coordPos - 2 * p - 1]; + } + + // --- reverse segment types --- + segmentTypes = new int[segPos]; + if (segPos > 0) { + boolean pendingClose = false; + int sr = 0; + segmentTypes[sr++] = SEG_MOVETO; + for (int s = segPos - 1; s > 0; --s) { + switch (segTypes[s]) { + case SEG_MOVETO: + if (pendingClose) { + pendingClose = false; + segmentTypes[sr++] = SEG_CLOSE; + } + segmentTypes[sr++] = SEG_MOVETO; + break; + case SEG_CLOSE: + pendingClose = true; + break; + default: + segmentTypes[sr++] = segTypes[s]; + break; + } + } + if (pendingClose) { + segmentTypes[sr] = SEG_CLOSE; + } + } + } + + /** + * Returns the winding rule for determining the interior of the + * path. + * + * @return the winding rule. + * @see #WIND_EVEN_ODD + * @see #WIND_NON_ZERO + */ + @Override + public int getWindingRule() { + return windingRule; + } + + /** + * Get the number of coordinates needed for a segment type. + * @param segtype segment type + * @return coordinates needed + */ + private static int coordinatesForSegmentType(int segtype) { + switch (segtype) { + case SEG_MOVETO: + case SEG_LINETO: + return 2; + case SEG_QUADTO: + return 4; + case SEG_CUBICTO: + return 6; + default: + return 0; + } + } + + /** + * Moves the iterator to the next segment of the path forwards + * along the primary direction of traversal as long as there are + * more points in that direction. + */ + @Override + public void next() { + coordIndex += coordinatesForSegmentType(segmentTypes[segmentIndex++]); + } + + /** + * Tests if the iteration is complete. + * + * @return true if all the segments have + * been read; false otherwise. + */ + @Override + public boolean isDone() { + return segmentIndex >= segmentTypes.length; + } + + /** + * Returns the coordinates and type of the current path segment in + * the iteration. + * The return value is the path-segment type: + * SEG_MOVETO, SEG_LINETO, SEG_QUADTO, SEG_CUBICTO, or SEG_CLOSE. + * A double array of length 6 must be passed in and can be used to + * store the coordinates of the point(s). + * Each point is stored as a pair of double x,y coordinates. + * SEG_MOVETO and SEG_LINETO types returns one point, + * SEG_QUADTO returns two points, + * SEG_CUBICTO returns 3 points + * and SEG_CLOSE does not return any points. + * + * @param coords an array that holds the data returned from + * this method + * @return the path-segment type of the current path segment. + * @see #SEG_MOVETO + * @see #SEG_LINETO + * @see #SEG_QUADTO + * @see #SEG_CUBICTO + * @see #SEG_CLOSE + */ + @Override + public int currentSegment(double[] coords) { + final int segmentType = segmentTypes[segmentIndex]; + final int copy = coordinatesForSegmentType(segmentType); + if (copy > 0) { + System.arraycopy(coordinates, coordIndex, coords, 0, copy); + } + return segmentType; + } + + /** + * Returns the coordinates and type of the current path segment in + * the iteration. + * The return value is the path-segment type: + * SEG_MOVETO, SEG_LINETO, SEG_QUADTO, SEG_CUBICTO, or SEG_CLOSE. + * A float array of length 6 must be passed in and can be used to + * store the coordinates of the point(s). + * Each point is stored as a pair of float x,y coordinates. + * SEG_MOVETO and SEG_LINETO types returns one point, + * SEG_QUADTO returns two points, + * SEG_CUBICTO returns 3 points + * and SEG_CLOSE does not return any points. + * + * @param coords an array that holds the data returned from + * this method + * @return the path-segment type of the current path segment. + * @see #SEG_MOVETO + * @see #SEG_LINETO + * @see #SEG_QUADTO + * @see #SEG_CUBICTO + * @see #SEG_CLOSE + */ + @Override + public int currentSegment(float[] coords) { + final int segmentType = segmentTypes[segmentIndex]; + final int copy = coordinatesForSegmentType(segmentType); + if (copy > 0) { + for (int c = 0; c < copy; ++c) { + coords[c] = (float) coordinates[coordIndex + c]; + } + } + return segmentType; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/util/SegmentIteratorWithLookBehind.java @@ -0,0 +1,185 @@ +/* + * MIT License + * + * Copyright (c) 2022-2026 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.geometry.util; + +import java.awt.geom.PathIterator; +import java.util.ArrayList; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.geometry.size.Length; + +public final class SegmentIteratorWithLookBehind { + + private final @NotNull PathIterator pathIterator; + private float maxLookBehindLength; + private float currentLookBehindLength = 0; + + private final ArrayList lookBehind = new ArrayList<>(); + private Segment currentSegment; + + private final float[] cords = new float[2]; + private float moveToX; + private float moveToY; + + private int lookBehindCursor = -1; + + + public SegmentIteratorWithLookBehind(@NotNull PathIterator pathIterator, float maxLookBehindLength) { + this.pathIterator = pathIterator; + this.maxLookBehindLength = maxLookBehindLength; + prepareFirstSegment(); + } + + private void prepareFirstSegment() { + this.currentSegment = new Segment( + Length.UNSPECIFIED_RAW, Length.UNSPECIFIED_RAW, + Length.UNSPECIFIED_RAW, Length.UNSPECIFIED_RAW); + moveToNext(); + if (Length.isUnspecified(currentSegment.xStart) || Length.isUnspecified(currentSegment.yStart)) { + throw new IllegalStateException("Path iterator did not establish starting position"); + } + } + + /* + * Do not modify while the iterator is still used. + */ + public @NotNull PathIterator pathIterator() { + return pathIterator; + } + + public void setMaxLookBehindLength(float maxLookBehindLength) { + this.maxLookBehindLength = maxLookBehindLength; + trimLookBehindIfNecessary(); + } + + public float maxLookBehindLength() { + return maxLookBehindLength; + } + + public boolean hasNext() { + return lookBehindCursor >= 0 || !pathIterator.isDone(); + } + + public boolean isDone() { + return !hasNext(); + } + + public boolean hasPrevious() { + return lookBehindCursor < lookBehind.size() - 1; + } + + public @NotNull Segment currentSegment() { + if (lookBehindCursor >= 0) { + return lookBehind.get(lookBehind.size() - 1 - lookBehindCursor); + } else { + return currentSegment; + } + } + + public void moveToPrevious() { + if (!hasPrevious()) { + throw new IllegalStateException("Can't move back anymore. Maximum capacity is " + maxLookBehindLength); + } + lookBehindCursor++; + } + + public void moveToNext() { + if (lookBehindCursor >= 0) { + lookBehindCursor--; + return; + } + Segment nextSegment = new Segment( + currentSegment.xEnd, currentSegment.yEnd, + Length.UNSPECIFIED_RAW, Length.UNSPECIFIED_RAW); + + outer: while (!pathIterator.isDone()) { + switch (pathIterator.currentSegment(cords)) { + case PathIterator.SEG_MOVETO: + nextSegment.xStart = moveToX = cords[0]; + nextSegment.yStart = moveToY = cords[1]; + nextSegment.moveHappened = true; + pathIterator.next(); + break; + case PathIterator.SEG_CLOSE: + nextSegment.xEnd = moveToX; + nextSegment.yEnd = moveToY; + pathIterator.next(); + break outer; + case PathIterator.SEG_LINETO: + nextSegment.xEnd = cords[0]; + nextSegment.yEnd = cords[1]; + pathIterator.next(); + break outer; + default: + throw new IllegalStateException("Unsupported segment type"); + } + } + if (Float.isNaN(nextSegment.xEnd) || Float.isNaN(nextSegment.yEnd)) { + nextSegment.xEnd = nextSegment.xStart; + nextSegment.yEnd = nextSegment.yStart; + } + + if (maxLookBehindLength > 0) { + lookBehind.add(currentSegment); + currentLookBehindLength += (float) currentSegment.length(); + + trimLookBehindIfNecessary(); + } + currentSegment = nextSegment; + } + + private void trimLookBehindIfNecessary() { + while (GeometryUtil.notablyGreater(currentLookBehindLength, maxLookBehindLength)) { + Segment segment = lookBehind.get(0); + double segmentLength = segment.length(); + if (this.currentLookBehindLength - segmentLength < maxLookBehindLength) break; + this.currentLookBehindLength -= (float) segmentLength; + lookBehind.remove(0); + } + } + + public static final class Segment { + public float xStart; + public float yStart; + public float xEnd; + public float yEnd; + + public boolean moveHappened; + + private Segment(float xStart, float yStart, float xEnd, float yEnd) { + this.xStart = xStart; + this.yStart = yStart; + this.xEnd = xEnd; + this.yEnd = yEnd; + } + + public double length() { + return GeometryUtil.lineLength(xStart, yStart, xEnd, yEnd); + } + + @Override + public String toString() { + return String.format("[%.2f,%.2f] -> [%.2f,%.2f] (moved: %b)", xStart, yStart, xEnd, yEnd, moveHappened); + } + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/util/TransformUtil.java @@ -0,0 +1,44 @@ +/* + * MIT License + * + * Copyright (c) 2024-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.geometry.util; + +import static com.github.weisj.jsvg.geometry.util.GeometryUtil.lerp; + +import java.awt.geom.AffineTransform; + +import org.jetbrains.annotations.NotNull; + +final class TransformUtil { + + private TransformUtil() {} + + static @NotNull AffineTransform interpolate(@NotNull AffineTransform a, @NotNull AffineTransform b, float t) { + double[] aEntries = new double[6]; + double[] bEntries = new double[6]; + a.getMatrix(aEntries); + b.getMatrix(bEntries); + for (int i = 0; i < aEntries.length; i++) { + aEntries[i] = lerp(t, aEntries[i], bEntries[i]); + } + return new AffineTransform(aEntries); + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/geometry/util/package-info.java @@ -0,0 +1,3 @@ +@org.osgi.annotation.bundle.Export +@aQute.bnd.annotation.jpms.ExportTo("com.github.weisj.jsvg.javafx") +package com.github.weisj.jsvg.geometry.util; --- /dev/null +++ b/src/com/github/weisj/jsvg/logging/LogManager.java @@ -0,0 +1,30 @@ +/* + * MIT License + * + * Copyright (c) 2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.logging; + +import org.jetbrains.annotations.NotNull; + +public interface LogManager { + + @NotNull + Logger createLogger(@NotNull String name); +} --- /dev/null +++ b/src/com/github/weisj/jsvg/logging/Logger.java @@ -0,0 +1,43 @@ +/* + * MIT License + * + * Copyright (c) 2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.logging; + +import java.util.function.Supplier; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public interface Logger { + + enum Level { + DEBUG, + INFO, + WARNING, + ERROR, + } + + void log(Level level, @Nullable String message); + + void log(Level level, @Nullable String message, @NotNull Throwable e); + + void log(Level level, @NotNull Supplier<@Nullable String> messageSupplier); +} --- /dev/null +++ b/src/com/github/weisj/jsvg/logging/impl/CallerFinder.java @@ -0,0 +1,122 @@ +/* + * MIT License + * + * Copyright (c) 2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.logging.impl; + +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; +import java.util.Optional; +import java.util.function.Function; +import java.util.stream.Stream; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +final class CallerFinder { + private static final boolean HAS_STACK_WALKER; + private static final MethodHandle STACK_WALKER_WALK; + private static final MethodHandle STACK_FRAME_GET_CLASS_NAME; + private static final MethodHandle STACK_FRAME_GET_METHOD_NAME; + + private final String dispatcherClassName; + private boolean lookingForCaller = false; + + static { + MethodHandle walk = null; + MethodHandle getClassName = null; + MethodHandle getMethodName = null; + boolean hasStackWalker = false; + try { + Class stackWalkerClass = Class.forName("java.lang.StackWalker"); + Class optionClass = Class.forName("java.lang.StackWalker$Option"); + @SuppressWarnings({"rawtypes", "unchecked"}) Object retainClassRef = + Enum.valueOf((Class) optionClass, "RETAIN_CLASS_REFERENCE"); + MethodHandle getInstance = MethodHandles.publicLookup().findStatic( + stackWalkerClass, "getInstance", + MethodType.methodType(stackWalkerClass, optionClass)); + Object stackWalkerInstance = getInstance.invoke(retainClassRef); + walk = MethodHandles.lookup().findVirtual( + stackWalkerClass, "walk", + MethodType.methodType(Object.class, java.util.function.Function.class)); + walk = walk.bindTo(stackWalkerInstance); + + Class stackFrameClass = Class.forName("java.lang.StackWalker$StackFrame"); + getClassName = MethodHandles.publicLookup().findVirtual( + stackFrameClass, "getClassName", MethodType.methodType(String.class)); + getMethodName = MethodHandles.publicLookup().findVirtual( + stackFrameClass, "getMethodName", MethodType.methodType(String.class)); + + hasStackWalker = true; + } catch (Throwable ignored) { + // If any of the above fails, we will not use the stack walker. + } + HAS_STACK_WALKER = hasStackWalker; + STACK_WALKER_WALK = walk; + STACK_FRAME_GET_CLASS_NAME = getClassName; + STACK_FRAME_GET_METHOD_NAME = getMethodName; + } + + public CallerFinder(@NotNull String dispatcherClassName) { + this.dispatcherClassName = dispatcherClassName; + } + + @SuppressWarnings("unchecked") + public Optional findCaller() { + if (HAS_STACK_WALKER) { + try { + return (Optional) STACK_WALKER_WALK.invoke( + (Function, Optional>) stream -> stream + .map(f -> { + try { + String className = (String) STACK_FRAME_GET_CLASS_NAME.invoke(f); + String methodName = (String) STACK_FRAME_GET_METHOD_NAME.invoke(f); + return new StackTraceElement(className, methodName, null, -1); + } catch (Throwable t) { + return null; + } + }) + .filter(this::isCallerFrame) + .findFirst()); + } catch (Throwable ignored) { + // If the stack walker fails, we will fall back to the traditional method. + } + } + // Fallback for JDK 8 + StackTraceElement[] stack = new Throwable().getStackTrace(); + for (StackTraceElement element : stack) { + if (isCallerFrame(element)) { + return Optional.of(element); + } + } + return Optional.empty(); + } + + private boolean isCallerFrame(@Nullable StackTraceElement frame) { + if (frame == null) return false; + String cname = frame.getClassName(); + if (!lookingForCaller) { + lookingForCaller = cname.equals(dispatcherClassName); + return false; + } + return true; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/logging/impl/LogFactory.java @@ -0,0 +1,35 @@ +/* + * MIT License + * + * Copyright (c) 2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.logging.impl; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.logging.Logger; + +public final class LogFactory { + + private LogFactory() {} + + public static @NotNull Logger createLogger(@NotNull Class clazz) { + return LogManagerImpl.logManager().createLogger(clazz.getName()); + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/logging/impl/LogManagerImpl.java @@ -0,0 +1,142 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.logging.impl; + +import java.util.Iterator; +import java.util.ServiceLoader; +import java.util.function.Supplier; +import java.util.logging.Level; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import com.github.weisj.jsvg.logging.LogManager; +import com.github.weisj.jsvg.logging.Logger; + +import aQute.bnd.annotation.spi.ServiceConsumer; + +@ServiceConsumer(value = LogManager.class) +@SuppressWarnings("SameNameButDifferent") +public final class LogManagerImpl { + private static final @NotNull LogManager logManager; + + private LogManagerImpl() {} + + static { + Iterator managers = ServiceLoader.load(LogManager.class).iterator(); + if (managers.hasNext()) { + logManager = managers.next(); + } else { + logManager = new DefaultLogManager(); + } + } + + public static @NotNull LogManager logManager() { + return logManager; + } + + private static class DefaultLogManager implements LogManager { + @Override + public @NotNull Logger createLogger(@NotNull String name) { + return new JavaUtilLoggerWrapper(java.util.logging.Logger.getLogger(name)); + } + } + + private static final class JavaUtilLoggerWrapper implements Logger { + private final @NotNull java.util.logging.Logger logger; + + private JavaUtilLoggerWrapper(@NotNull java.util.logging.Logger logger) { + this.logger = logger; + } + + @Override + public void log(Level level, @Nullable String message) { + logger.log(new WrapperLogRecord(toJavaUtilLevel(level), message)); + } + + @Override + public void log(Level level, @Nullable String message, @NotNull Throwable e) { + WrapperLogRecord logRecord = new WrapperLogRecord(toJavaUtilLevel(level), message); + logRecord.setThrown(e); + logger.log(logRecord); + } + + @Override + public void log(Level level, @NotNull Supplier<@Nullable String> messageSupplier) { + java.util.logging.Level javaUtilLevel = toJavaUtilLevel(level); + if (!logger.isLoggable(javaUtilLevel)) { + return; + } + logger.log(new WrapperLogRecord(javaUtilLevel, messageSupplier.get())); + } + + static java.util.logging.Level toJavaUtilLevel(@NotNull Logger.Level level) { + switch (level) { + case DEBUG: + return java.util.logging.Level.FINE; + case INFO: + return java.util.logging.Level.INFO; + case WARNING: + return java.util.logging.Level.WARNING; + case ERROR: + return java.util.logging.Level.SEVERE; + default: + throw new IllegalArgumentException("Unknown log level: " + level); + } + } + } + + private static final class WrapperLogRecord extends java.util.logging.LogRecord { + private static final String DISPATCHER_CLASS_NAME = JavaUtilLoggerWrapper.class.getName(); + private boolean needToInferCaller = true; + + public WrapperLogRecord(Level level, String msg) { + super(level, msg); + } + + @Override + public String getSourceClassName() { + if (needToInferCaller) { + customInferCaller(); + } + return super.getSourceClassName(); + } + + @Override + public String getSourceMethodName() { + if (needToInferCaller) { + customInferCaller(); + } + return super.getSourceMethodName(); + } + + private void customInferCaller() { + needToInferCaller = false; + new CallerFinder(DISPATCHER_CLASS_NAME) + .findCaller() + .ifPresent(st -> { + setSourceClassName(st.getClassName()); + setSourceMethodName(st.getMethodName()); + }); + } + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/logging/package-info.java @@ -0,0 +1,2 @@ +@org.osgi.annotation.bundle.Export +package com.github.weisj.jsvg.logging; --- /dev/null +++ b/src/com/github/weisj/jsvg/nodes/AbstractGradient.java @@ -0,0 +1,226 @@ +/* + * MIT License + * + * Copyright (c) 2021-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.nodes; + +import java.awt.*; +import java.awt.geom.AffineTransform; +import java.awt.geom.Rectangle2D; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import com.github.weisj.jsvg.attributes.SpreadMethod; +import com.github.weisj.jsvg.attributes.UnitType; +import com.github.weisj.jsvg.attributes.value.TransformValue; +import com.github.weisj.jsvg.geometry.size.Percentage; +import com.github.weisj.jsvg.nodes.container.ContainerNode; +import com.github.weisj.jsvg.paint.SVGPaint; +import com.github.weisj.jsvg.parser.PaintParser; +import com.github.weisj.jsvg.parser.impl.AttributeNode; +import com.github.weisj.jsvg.parser.impl.AttributeNode.ElementRelation; +import com.github.weisj.jsvg.renderer.MeasureContext; +import com.github.weisj.jsvg.renderer.RenderContext; +import com.github.weisj.jsvg.renderer.output.Output; + +@SuppressWarnings("java:S119") // Generic name Self is intentional +abstract class AbstractGradient> extends ContainerNode implements SVGPaint { + protected TransformValue gradientTransform; + protected UnitType gradientUnits; + protected SpreadMethod spreadMethod; + + private @NotNull Color[] colors; + private Percentage[] offsets; + + private float[] tmpFractions; + + public final Percentage[] offsets() { + return offsets; + } + + public final @NotNull Color[] colors() { + return colors; + } + + @Override + public final void build(@NotNull AttributeNode attributeNode) { + super.build(attributeNode); + + AbstractGradient template = parseTemplate(attributeNode); + + gradientUnits = attributeNode.getEnum("gradientUnits", + template != null ? template.gradientUnits : UnitType.ObjectBoundingBox); + spreadMethod = attributeNode.getEnum("spreadMethod", + template != null ? template.spreadMethod : SpreadMethod.Pad); + + gradientTransform = attributeNode.parseTransform("gradientTransform"); + if (gradientTransform == null && template != null) + gradientTransform = template.gradientTransform; + + + List stops = childrenOfType(Stop.class); + if (stops.isEmpty() && template != null) { + colors = template.colors(); + offsets = template.offsets(); + } else { + parseStops(stops); + } + + // noinspection unchecked + Self selfTemplate = getClass().isInstance(template) ? (Self) template : null; + buildGradient(attributeNode, selfTemplate); + children().clear(); + } + + private void parseStops(@NotNull List stops) { + stops.sort(Comparator.comparing(Stop::offset)); + List colorsList = new ArrayList<>(); + List offsetsList = new ArrayList<>(); + + boolean realGradient = false; + for (Stop stop : stops) { + // Clamp the offset + float stopOffset = Math.max(0, Math.min(1, stop.offset().value())); + Color stopColor = stop.color(); + + boolean isFirstStop = offsetsList.isEmpty(); + boolean effectiveStop = isFirstStop + || isEffectiveStop(stopOffset, stopColor, offsetsList, colorsList); + realGradient = !isFirstStop && effectiveStop; + + if (isFirstStop && stopOffset != 0) { + // If the first stop is not at 0, we need to add a transparent color at the beginning. + offsetsList.add(Percentage.ZERO); + colorsList.add(stopColor); + } + + if (effectiveStop) { + offsetsList.add(new Percentage(stopOffset)); + colorsList.add(stopColor); + } + } + + if (!offsetsList.isEmpty() && offsetsList.get(offsetsList.size() - 1).value() != 1f) { + // If the last stop is not at 1, we need to add a transparent color at the end. + offsetsList.add(Percentage.ONE); + colorsList.add(colorsList.get(colorsList.size() - 1)); + } + + if (!realGradient && !colorsList.isEmpty()) { + // If all stops are equal, we can just use the first color. + // This never gets passed to the radial gradient hence we don't need to provide a second stop. + colors = new Color[] {colorsList.get(0)}; + offsets = new Percentage[] {Percentage.ZERO}; + } else { + colors = colorsList.toArray(new Color[0]); + offsets = offsetsList.toArray(new Percentage[0]); + makeStrictlyIncreasing(offsets); + } + } + + private static void makeStrictlyIncreasing(@NotNull Percentage @NotNull [] offsets) { + // Round up equal values to the next float value. + for (int i = 1; i < offsets.length; i++) { + if (offsets[i].value() <= offsets[i - 1].value()) { + offsets[i] = new Percentage(Math.nextUp(offsets[i - 1].value())); + } + } + + // Values have possibly exceeded 1 now. Clamp them back down. + for (int i = offsets.length - 1; i >= 0; i--) { + if (offsets[i].value() >= 1) { + offsets[i] = Percentage.ONE; + } + } + + // Now round values down as in step one but from top to bottom. + // Note: As there are 126 x 2^23 + 1 floats between 0 and 1 and we don't expect input array to be + // that large we can safely assume that now all values are distinct (as there will be a gap with + // enough space to shift all offsets to). + for (int i = offsets.length - 2; i >= 0; i--) { + if (offsets[i].value() >= offsets[i + 1].value()) { + offsets[i] = new Percentage(Math.nextDown(offsets[i + 1].value())); + } + } + } + + private static boolean isEffectiveStop(float stopOffset, @NotNull Color stopColor, + @NotNull List<@NotNull Percentage> offsetsList, + @NotNull List<@NotNull Color> colorsList) { + return stopOffset > offsetsList.get(offsetsList.size() - 1).value() + || !stopColor.equals(colorsList.get(colorsList.size() - 1)); + } + + private @Nullable AbstractGradient parseTemplate(@NotNull AttributeNode attributeNode) { + AbstractGradient template = attributeNode.getElementByHref(AbstractGradient.class, attributeNode.getHref(), + ElementRelation.TEMPLATE); + return template != this ? template : null; + } + + protected abstract void buildGradient(@NotNull AttributeNode attributeNode, @Nullable Self template); + + @Override + public void fillShape(@NotNull Output output, @NotNull RenderContext context, @NotNull Shape shape, + @Nullable Rectangle2D bounds) { + Rectangle2D b = bounds != null ? bounds : shape.getBounds2D(); + output.setPaint(() -> paintForBounds(context.measureContext(), b)); + output.fillShape(shape); + } + + @Override + public void drawShape(@NotNull Output output, @NotNull RenderContext context, @NotNull Shape shape, + @Nullable Rectangle2D bounds) { + Rectangle2D b = bounds != null ? bounds : shape.getBounds2D(); + output.setPaint(() -> paintForBounds(context.measureContext(), b)); + output.drawShape(shape); + } + + private @NotNull Paint paintForBounds(@NotNull MeasureContext context, @NotNull Rectangle2D bounds) { + Color[] gradColors = colors(); + if (gradColors.length == 0) return PaintParser.DEFAULT_COLOR; + if (gradColors.length == 1) return gradColors[0]; + return gradientForBounds(gradientUnits.deriveMeasure(context), bounds, offsets(), gradColors); + } + + protected float[] offsetsToFractions(Percentage[] gradOffsets) { + // NOTE: We need to recompute the fractions if a stop is animated. + if (tmpFractions == null || tmpFractions.length != gradOffsets.length) { + tmpFractions = new float[gradOffsets.length]; + for (int i = 0; i < tmpFractions.length; i++) { + tmpFractions[i] = gradOffsets[i].value(); + } + } + return tmpFractions; + } + + protected abstract @NotNull Paint gradientForBounds(@NotNull MeasureContext measure, @NotNull Rectangle2D bounds, + Percentage[] gradOffsets, @NotNull Color[] gradColors); + + protected final @NotNull AffineTransform computeViewTransform(@NotNull MeasureContext measure, + @NotNull Rectangle2D bounds) { + AffineTransform viewTransform = gradientUnits.viewTransform(bounds); + if (gradientTransform != null) viewTransform.concatenate(gradientTransform.get(measure)); + return viewTransform; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/nodes/AbstractPolyShape.java @@ -0,0 +1,58 @@ +/* + * MIT License + * + * Copyright (c) 2021-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.nodes; + +import java.awt.*; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.animation.value.AnimatedFloatList; +import com.github.weisj.jsvg.animation.value.AnimatedPath; +import com.github.weisj.jsvg.attributes.Animatable; +import com.github.weisj.jsvg.attributes.Inherited; +import com.github.weisj.jsvg.attributes.value.ConstantFloatList; +import com.github.weisj.jsvg.attributes.value.ConstantValue; +import com.github.weisj.jsvg.attributes.value.FloatListValue; +import com.github.weisj.jsvg.geometry.*; +import com.github.weisj.jsvg.parser.impl.AttributeNode; +import com.github.weisj.jsvg.util.PathUtil; + +public abstract class AbstractPolyShape extends ShapeNode { + + @Override + protected final @NotNull SVGShape buildShape(@NotNull AttributeNode attributeNode) { + FloatListValue points = attributeNode.getFloatList("points", Inherited.NO, Animatable.YES); + if (points instanceof AnimatedFloatList) { + return new FillRuleAwareAWTSVGShape(new AnimatedPath((AnimatedFloatList) points, doClose())); + } + + float[] pointsArray = ((ConstantFloatList) points).value(); + if (pointsArray.length > 0) { + return new FillRuleAwareAWTSVGShape( + new ConstantValue<>(PathUtil.setPolyLine(null, pointsArray, doClose()))); + } else { + return new AWTSVGShape<>(new Rectangle()); + } + } + + protected abstract boolean doClose(); +} --- /dev/null +++ b/src/com/github/weisj/jsvg/nodes/AbstractSVGNode.java @@ -0,0 +1,49 @@ +/* + * MIT License + * + * Copyright (c) 2021-2025 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.nodes; + + +import org.jetbrains.annotations.MustBeInvokedByOverriders; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import com.github.weisj.jsvg.parser.impl.AttributeNode; + +public abstract class AbstractSVGNode implements SVGNode { + private @Nullable String id; + + @Override + public @Nullable String id() { + return id; + } + + @Override + @MustBeInvokedByOverriders + public void build(@NotNull AttributeNode attributeNode) { + id = attributeNode.getValue("id"); + } + + @Override + public String toString() { + return getClass().getSimpleName() + "{id='" + id + '\'' + '}'; + } +} --- /dev/null +++ b/src/com/github/weisj/jsvg/nodes/Anchor.java @@ -0,0 +1,55 @@ +/* + * MIT License + * + * Copyright (c) 2021-2022 Jannis Weis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package com.github.weisj.jsvg.nodes; + +import org.jetbrains.annotations.NotNull; + +import com.github.weisj.jsvg.nodes.container.CommonRenderableContainerNode; +import com.github.weisj.jsvg.nodes.filter.Filter; +import com.github.weisj.jsvg.nodes.prototype.ShapedContainer; +import com.github.weisj.jsvg.nodes.prototype.spec.Category; +import com.github.weisj.jsvg.nodes.prototype.spec.ElementCategories; +import com.github.weisj.jsvg.nodes.prototype.spec.PermittedContent; +import com.github.weisj.jsvg.nodes.text.Text; + +/** + * As jsvg is only a static renderer without interaction the anchor tag behaves just as if it were a + * group. + */ +@ElementCategories(Category.Container) +@PermittedContent( + categories = {Category.Container, Category.Descriptive, Category.Shape, Category.Structural, Category.Gradient, + Category.Animation}, + /* + * , , , , ,