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;
}
}
private XMLReader getXMLReaderCached() throws SAXException, ParserConfigurationException
{
if (cachedReader == null)
{
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
cachedReader = factory.newSAXParser().getXMLReader();
}
return cachedReader;
}
protected URI loadSVG(URI xmlBase, InputSource is)
{
// 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 = getXMLReaderCached();
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)
{
System.err.println("Error processing " + xmlBase);
System.err.println(sex.getMessage());
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)
{
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;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/ShapeElement.java 0000664 0000000 0000000 00000035431 12756023445 0026576 0 ustar 00root root 0000000 0000000 /*
* 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() {
}
abstract public void render(java.awt.Graphics2D g) throws SVGException;
/*
protected void setStrokeWidthScalar(float strokeWidthScalar)
{
this.strokeWidthScalar = strokeWidthScalar;
}
*/
void pick(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));
}
}
void pick(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 = (MarkerPos)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;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/Stop.java 0000664 0000000 0000000 00000010334 12756023445 0025144 0 ustar 00root root 0000000 0000000 /*
* 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()
{
}
public String getTagName()
{
return TAG_NAME;
}
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
*/
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;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/Style.java 0000664 0000000 0000000 00000006145 12756023445 0025324 0 ustar 00root root 0000000 0000000 /*
* 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()
{
}
public String getTagName()
{
return TAG_NAME;
}
/**
* Called during load process to add text scanned within a tag
*/
public void loaderAddText(SVGLoaderHelper helper, String text)
{
this.text.append(text);
//Invalidate style sheet
styleSheet = null;
}
protected void build() throws SVGException
{
super.build();
StyleAttribute sty = new StyleAttribute();
if (getPres(sty.setName("type")))
{
type = sty.getStringValue();
}
}
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;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/Symbol.java 0000664 0000000 0000000 00000010656 12756023445 0025473 0 ustar 00root root 0000000 0000000 /*
* 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()
{
}
public String getTagName()
{
return TAG_NAME;
}
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());
}
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;
}
public void render(Graphics2D g) throws SVGException
{
AffineTransform oldXform = g.getTransform();
g.transform(viewXform);
super.render(g);
g.setTransform(oldXform);
}
public Shape getShape()
{
Shape shape = super.getShape();
return viewXform.createTransformedShape(shape);
}
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
*/
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;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/Text.java 0000664 0000000 0000000 00000046442 12756023445 0025154 0 ustar 00root root 0000000 0000000 /*
* 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.FontSystem;
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.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Mark McKay
* @author Mark McKay
*/
public class Text extends ShapeElement
{
public static final String TAG_NAME = "text";
float x = 0;
float y = 0;
AffineTransform transform = null;
String fontFamily;
float fontSize;
//List of strings and tspans containing the content of this node
LinkedList content = new LinkedList();
Shape textShape;
public static final int TXAN_START = 0;
public static final int TXAN_MIDDLE = 1;
public static final int TXAN_END = 2;
int textAnchor = TXAN_START;
public static final int TXST_NORMAL = 0;
public static final int TXST_ITALIC = 1;
public static final int TXST_OBLIQUE = 2;
int fontStyle;
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 fontWeight;
float textLength = -1;
String lengthAdjust = "spacing";
/**
* Creates a new instance of Stop
*/
public Text()
{
}
public String getTagName()
{
return TAG_NAME;
}
public void appendText(String text)
{
content.addLast(text);
}
public void appendTspan(Tspan tspan) throws SVGElementException
{
super.loaderAddChild(null, tspan);
content.addLast(tspan);
}
/**
* Discard cached information
*/
public void rebuild() throws SVGException
{
build();
}
public java.util.List getContent()
{
return content;
}
/**
* Called after the start element but before the end element to indicate
* each child tag that has been processed
*/
public void loaderAddChild(SVGLoaderHelper helper, SVGElement child) throws SVGElementException
{
super.loaderAddChild(helper, child);
content.addLast(child);
}
/**
* Called during load process to add text scanned within a tag
*/
public void loaderAddText(SVGLoaderHelper helper, String text)
{
Matcher matchWs = Pattern.compile("\\s*").matcher(text);
if (!matchWs.matches())
{
content.addLast(text);
}
}
public 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 (getStyle(sty.setName("font-family")))
{
fontFamily = sty.getStringValue();
}
else
{
fontFamily = "Sans Serif";
}
if (getStyle(sty.setName("font-size")))
{
fontSize = sty.getFloatValueWithUnits();
}
else
{
fontSize = 12f;
}
if (getStyle(sty.setName("textLength")))
{
textLength = sty.getFloatValueWithUnits();
}
else
{
textLength = -1;
}
if (getStyle(sty.setName("lengthAdjust")))
{
lengthAdjust = sty.getStringValue();
}
else
{
lengthAdjust = "spacing";
}
if (getStyle(sty.setName("font-style")))
{
String s = sty.getStringValue();
if ("normal".equals(s))
{
fontStyle = TXST_NORMAL;
} else if ("italic".equals(s))
{
fontStyle = TXST_ITALIC;
} else if ("oblique".equals(s))
{
fontStyle = TXST_OBLIQUE;
}
} else
{
fontStyle = TXST_NORMAL;
}
if (getStyle(sty.setName("font-weight")))
{
String s = sty.getStringValue();
if ("normal".equals(s))
{
fontWeight = TXWE_NORMAL;
} else if ("bold".equals(s))
{
fontWeight = TXWE_BOLD;
}
} else
{
fontWeight = TXWE_NORMAL;
}
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;
}
//text anchor
//text-decoration
//text-rendering
buildText();
}
protected void buildText() throws SVGException
{
//Get font
String[] families = fontFamily.split(",");
Font font = null;
for (int i = 0; i < families.length; ++i)
{
font = diagram.getUniverse().getFont(fontFamily);
if (font != null)
{
break;
}
}
if (font == null)
{
// System.err.println("Could not load font");
font = new FontSystem(fontFamily, fontStyle, fontWeight, (int)fontSize);
// java.awt.Font sysFont = new java.awt.Font(fontFamily, style | weight, (int)fontSize);
// buildSysFont(sysFont);
// return;
}
// font = new java.awt.Font(font.getFamily(), style | weight, font.getSize());
// Area textArea = new Area();
GeneralPath textPath = new GeneralPath();
textShape = textPath;
float cursorX = x, cursorY = y;
FontFace fontFace = font.getFontFace();
//int unitsPerEm = fontFace.getUnitsPerEm();
// int ascent = fontFace.getAscent();
// float fontScale = fontSize / (float) ascent;
// AffineTransform oldXform = g.getTransform();
// TextBuilder builder = new TextBuilder();
//
// for (Iterator it = content.iterator(); it.hasNext();)
// {
// Object obj = it.next();
//
// if (obj instanceof String)
// {
// String text = (String) obj;
// if (text != null)
// {
// text = text.trim();
// }
//
// for (int i = 0; i < text.length(); i++)
// {
// String unicode = text.substring(i, i + 1);
// MissingGlyph glyph = font.getGlyph(unicode);
//
// builder.appendGlyph(glyph);
// }
// }
// else if (obj instanceof Tspan)
// {
// Tspan tspan = (Tspan)obj;
// tspan.buildGlyphs(builder);
// }
// }
//
// builder.formatGlyphs();
AffineTransform xform = new AffineTransform();
for (Iterator it = content.iterator(); it.hasNext();)
{
Object obj = it.next();
if (obj instanceof String)
{
String text = (String) obj;
if (text != null)
{
text = text.trim();
}
// strokeWidthScalar = 1f / fontScale;
for (int i = 0; i < text.length(); i++)
{
xform.setToIdentity();
xform.setToTranslation(cursorX, cursorY);
// xform.scale(fontScale, fontScale);
// g.transform(xform);
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);
}
// else glyph.render(g);
// cursorX += fontScale * glyph.getHorizAdvX();
cursorX += glyph.getHorizAdvX();
// g.setTransform(oldXform);
}
strokeWidthScalar = 1f;
}
else if (obj instanceof Tspan)
{
// Tspan tspan = (Tspan) obj;
//
// xform.setToIdentity();
// xform.setToTranslation(cursorX, cursorY);
// xform.scale(fontScale, fontScale);
//// tspan.setCursorX(cursorX);
//// tspan.setCursorY(cursorY);
//
// Shape tspanShape = tspan.getShape();
// tspanShape = xform.createTransformedShape(tspanShape);
// textPath.append(tspanShape, false);
//// tspan.render(g);
//// cursorX = tspan.getCursorX();
//// cursorY = tspan.getCursorY();
Tspan tspan = (Tspan)obj;
Point2D cursor = new Point2D.Float(cursorX, cursorY);
// tspan.setCursorX(cursorX);
// tspan.setCursorY(cursorY);
tspan.appendToShape(textPath, cursor);
// cursorX = tspan.getCursorX();
// cursorY = tspan.getCursorY();
cursorX = (float)cursor.getX();
cursorY = (float)cursor.getY();
}
}
switch (textAnchor)
{
case TXAN_MIDDLE:
{
AffineTransform at = new AffineTransform();
at.translate(-textPath.getBounds().getWidth() / 2, 0);
textPath.transform(at);
break;
}
case TXAN_END:
{
AffineTransform at = new AffineTransform();
at.translate(-textPath.getBounds().getWidth(), 0);
textPath.transform(at);
break;
}
}
}
// private void buildSysFont(java.awt.Font font) throws SVGException
// {
// GeneralPath textPath = new GeneralPath();
// textShape = textPath;
//
// float cursorX = x, cursorY = y;
//
//// FontMetrics fm = g.getFontMetrics(font);
// FontRenderContext frc = new FontRenderContext(null, true, true);
//
//// FontFace fontFace = font.getFontFace();
// //int unitsPerEm = fontFace.getUnitsPerEm();
//// int ascent = fm.getAscent();
//// float fontScale = fontSize / (float)ascent;
//
//// AffineTransform oldXform = g.getTransform();
// AffineTransform xform = new AffineTransform();
//
// for (Iterator it = content.iterator(); it.hasNext();)
// {
// Object obj = it.next();
//
// if (obj instanceof String)
// {
// String text = (String)obj;
// text = text.trim();
//
// Shape textShape = font.createGlyphVector(frc, text).getOutline(cursorX, cursorY);
// textPath.append(textShape, false);
//// renderShape(g, textShape);
//// g.drawString(text, cursorX, cursorY);
//
// Rectangle2D rect = font.getStringBounds(text, frc);
// cursorX += (float) rect.getWidth();
// } else if (obj instanceof Tspan)
// {
// /*
// Tspan tspan = (Tspan)obj;
//
// xform.setToIdentity();
// xform.setToTranslation(cursorX, cursorY);
//
// Shape tspanShape = tspan.getShape();
// tspanShape = xform.createTransformedShape(tspanShape);
// textArea.add(new Area(tspanShape));
//
// cursorX += tspanShape.getBounds2D().getWidth();
// */
//
//
// Tspan tspan = (Tspan)obj;
// Point2D cursor = new Point2D.Float(cursorX, cursorY);
//// tspan.setCursorX(cursorX);
//// tspan.setCursorY(cursorY);
// tspan.appendToShape(textPath, cursor);
//// cursorX = tspan.getCursorX();
//// cursorY = tspan.getCursorY();
// cursorX = (float)cursor.getX();
// cursorY = (float)cursor.getY();
//
// }
// }
//
// switch (textAnchor)
// {
// case TXAN_MIDDLE:
// {
// AffineTransform at = new AffineTransform();
// at.translate(-textPath.getBounds().getWidth() / 2, 0);
// textPath.transform(at);
// break;
// }
// case TXAN_END:
// {
// AffineTransform at = new AffineTransform();
// at.translate(-Math.ceil(textPath.getBounds().getWidth()), 0);
// textPath.transform(at);
// break;
// }
// }
// }
public void render(Graphics2D g) throws SVGException
{
beginLayer(g);
renderShape(g, textShape);
finishLayer(g);
}
public Shape getShape()
{
return shapeToParent(textShape);
}
public Rectangle2D getBoundingBox() throws SVGException
{
return boundsToParent(includeStrokeInBounds(textShape.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
*/
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 (getStyle(sty.setName("textLength")))
{
textLength = sty.getFloatValueWithUnits();
}
else
{
textLength = -1;
}
if (getStyle(sty.setName("lengthAdjust")))
{
lengthAdjust = sty.getStringValue();
}
else
{
lengthAdjust = "spacing";
}
if (getPres(sty.setName("font-family")))
{
String newVal = sty.getStringValue();
if (!newVal.equals(fontFamily))
{
fontFamily = newVal;
shapeChange = true;
}
}
if (getPres(sty.setName("font-size")))
{
float newVal = sty.getFloatValueWithUnits();
if (newVal != fontSize)
{
fontSize = newVal;
shapeChange = true;
}
}
if (getStyle(sty.setName("font-style")))
{
String s = sty.getStringValue();
int newVal = fontStyle;
if ("normal".equals(s))
{
newVal = TXST_NORMAL;
} else if ("italic".equals(s))
{
newVal = TXST_ITALIC;
} else if ("oblique".equals(s))
{
newVal = TXST_OBLIQUE;
}
if (newVal != fontStyle)
{
fontStyle = newVal;
shapeChange = true;
}
}
if (getStyle(sty.setName("font-weight")))
{
String s = sty.getStringValue();
int newVal = fontWeight;
if ("normal".equals(s))
{
newVal = TXWE_NORMAL;
} else if ("bold".equals(s))
{
newVal = TXWE_BOLD;
}
if (newVal != fontWeight)
{
fontWeight = newVal;
shapeChange = true;
}
}
if (shapeChange)
{
build();
// buildFont();
// return true;
}
return changeState || shapeChange;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/Title.java 0000664 0000000 0000000 00000005332 12756023445 0025302 0 ustar 00root root 0000000 0000000 /*
* 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()
{
}
public String getTagName()
{
return TAG_NAME;
}
/**
* Called during load process to add text scanned within a tag
*/
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
*/
public boolean updateTime(double curTime) throws SVGException
{
//Title does not change
return false;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/TransformableElement.java 0000664 0000000 0000000 00000010306 12756023445 0030327 0 ustar 00root root 0000000 0000000 /*
* 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);
}
}
*/
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)
{
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
*/
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;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/Tspan.java 0000664 0000000 0000000 00000034246 12756023445 0025314 0 ustar 00root root 0000000 0000000 /*
* 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.FontSystem;
import com.kitfox.svg.xml.StyleAttribute;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphMetrics;
import java.awt.font.GlyphVector;
import java.awt.geom.AffineTransform;
import java.awt.geom.GeneralPath;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
/**
* @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;
private String text = "";
// float cursorX;
// float cursorY;
// Shape tspanShape;
/**
* Creates a new instance of Stop
*/
public Tspan()
{
}
public String getTagName()
{
return TAG_NAME;
}
// public float getCursorX()
// {
// return cursorX;
// }
//
// public float getCursorY()
// {
// return cursorY;
// }
//
// public void setCursorX(float cursorX)
// {
// this.cursorX = cursorX;
// }
//
// public void setCursorY(float cursorY)
// {
// this.cursorY = cursorY;
// }
/*
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 dx = attrs.getValue("dx");
String dy = attrs.getValue("dy");
String rotate = attrs.getValue("rotate");
if (x != null) this.x = XMLParseUtil.parseFloatList(x);
if (y != null) this.y = XMLParseUtil.parseFloatList(y);
if (dx != null) this.dx = XMLParseUtil.parseFloatList(dx);
if (dy != null) this.dy = XMLParseUtil.parseFloatList(dy);
if (rotate != null)
{
this.rotate = XMLParseUtil.parseFloatList(rotate);
for (int i = 0; i < this.rotate.length; i++)
this.rotate[i] = (float)Math.toRadians(this.rotate[i]);
}
}
*/
/**
* Called during load process to add text scanned within a tag
*/
public void loaderAddText(SVGLoaderHelper helper, String text)
{
this.text += text;
}
protected void build() throws SVGException
{
super.build();
StyleAttribute sty = new StyleAttribute();
if (getPres(sty.setName("x")))
{
x = sty.getFloatList();
}
if (getPres(sty.setName("y")))
{
y = sty.getFloatList();
}
if (getPres(sty.setName("dx")))
{
dx = sty.getFloatList();
}
if (getPres(sty.setName("dy")))
{
dy = sty.getFloatList();
}
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]);
}
}
}
public void appendToShape(GeneralPath addShape, Point2D cursor) throws SVGException
{
StyleAttribute sty = new StyleAttribute();
String fontFamily = null;
if (getStyle(sty.setName("font-family")))
{
fontFamily = sty.getStringValue();
}
float fontSize = 12f;
if (getStyle(sty.setName("font-size")))
{
fontSize = sty.getFloatValueWithUnits();
}
float letterSpacing = 0;
if (getStyle(sty.setName("letter-spacing")))
{
letterSpacing = sty.getFloatValueWithUnits();
}
int fontStyle = 0;
if (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;
}
} else
{
fontStyle = Text.TXST_NORMAL;
}
int fontWeight = 0;
if (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;
}
} else
{
fontWeight = Text.TXWE_NORMAL;
}
//Get font
Font font = diagram.getUniverse().getFont(fontFamily);
if (font == null)
{
font = new FontSystem(fontFamily, fontStyle, fontWeight, (int)fontSize);
// addShapeSysFont(addShape, font, fontFamily, fontSize, letterSpacing, cursor);
// return;
}
FontFace fontFace = font.getFontFace();
// int ascent = fontFace.getAscent();
// float fontScale = fontSize / (float) ascent;
AffineTransform xform = new AffineTransform();
// strokeWidthScalar = 1f / fontScale;
float cursorX = (float)cursor.getX();
float cursorY = (float)cursor.getY();
// int i = 0;
String drawText = this.text;
drawText = drawText.trim();
for (int i = 0; i < drawText.length(); i++)
{
if (x != null && i < x.length)
{
cursorX = x[i];
} else if (dx != null && i < dx.length)
{
cursorX += dx[i];
}
if (y != null && i < y.length)
{
cursorY = y[i];
} else if (dy != null && i < dy.length)
{
cursorY += dy[i];
}
// i++;
xform.setToIdentity();
xform.setToTranslation(cursorX, cursorY);
// xform.scale(fontScale, fontScale);
if (rotate != null)
{
xform.rotate(rotate[i]);
}
String unicode = drawText.substring(i, i + 1);
MissingGlyph glyph = font.getGlyph(unicode);
Shape path = glyph.getPath();
if (path != null)
{
path = xform.createTransformedShape(path);
addShape.append(path, false);
}
// cursorX += fontScale * glyph.getHorizAdvX() + letterSpacing;
cursorX += glyph.getHorizAdvX() + letterSpacing;
}
//Save final draw point so calling method knows where to begin next
// text draw
cursor.setLocation(cursorX, cursorY);
strokeWidthScalar = 1f;
}
// private void addShapeSysFont(GeneralPath addShape, Font font,
// String fontFamily, float fontSize, float letterSpacing, Point2D cursor)
// {
//
// java.awt.Font sysFont = new java.awt.Font(fontFamily, java.awt.Font.PLAIN, (int) fontSize);
//
// FontRenderContext frc = new FontRenderContext(null, true, true);
// String renderText = this.text.trim();
//
// AffineTransform xform = new AffineTransform();
//
// float cursorX = (float)cursor.getX();
// float cursorY = (float)cursor.getY();
//// int i = 0;
// for (int i = 0; i < renderText.length(); i++)
// {
// if (x != null && i < x.length)
// {
// cursorX = x[i];
// } else if (dx != null && i < dx.length)
// {
// cursorX += dx[i];
// }
//
// if (y != null && i < y.length)
// {
// cursorY = y[i];
// } else if (dy != null && i < dy.length)
// {
// cursorY += dy[i];
// }
//// i++;
//
// xform.setToIdentity();
// xform.setToTranslation(cursorX, cursorY);
// if (rotate != null)
// {
// xform.rotate(rotate[Math.min(i, rotate.length - 1)]);
// }
//
//// String unicode = renderText.substring(i, i + 1);
// GlyphVector textVector = sysFont.createGlyphVector(frc, renderText.substring(i, i + 1));
// Shape glyphOutline = textVector.getGlyphOutline(0);
// GlyphMetrics glyphMetrics = textVector.getGlyphMetrics(0);
//
// glyphOutline = xform.createTransformedShape(glyphOutline);
// addShape.append(glyphOutline, false);
//
//
//// cursorX += fontScale * glyph.getHorizAdvX() + letterSpacing;
// cursorX += glyphMetrics.getAdvance() + letterSpacing;
// }
//
// cursor.setLocation(cursorX, cursorY);
// }
public void render(Graphics2D g) throws SVGException
{
float cursorX = 0;
float cursorY = 0;
if (x != null)
{
cursorX = x[0];
cursorY = y[0];
} else if (dx != null)
{
cursorX += dx[0];
cursorY += dy[0];
}
StyleAttribute sty = new StyleAttribute();
String fontFamily = null;
if (getPres(sty.setName("font-family")))
{
fontFamily = sty.getStringValue();
}
float fontSize = 12f;
if (getPres(sty.setName("font-size")))
{
fontSize = sty.getFloatValueWithUnits();
}
//Get font
Font font = diagram.getUniverse().getFont(fontFamily);
if (font == null)
{
System.err.println("Could not load font");
java.awt.Font sysFont = new java.awt.Font(fontFamily, java.awt.Font.PLAIN, (int) fontSize);
renderSysFont(g, sysFont);
return;
}
FontFace fontFace = font.getFontFace();
int ascent = fontFace.getAscent();
float fontScale = fontSize / (float) ascent;
AffineTransform oldXform = g.getTransform();
AffineTransform xform = new AffineTransform();
strokeWidthScalar = 1f / fontScale;
int posPtr = 1;
for (int i = 0; i < text.length(); i++)
{
xform.setToTranslation(cursorX, cursorY);
xform.scale(fontScale, fontScale);
g.transform(xform);
String unicode = text.substring(i, i + 1);
MissingGlyph glyph = font.getGlyph(unicode);
Shape path = glyph.getPath();
if (path != null)
{
renderShape(g, path);
} else
{
glyph.render(g);
}
if (x != null && posPtr < x.length)
{
cursorX = x[posPtr];
cursorY = y[posPtr++];
} else if (dx != null && posPtr < dx.length)
{
cursorX += dx[posPtr];
cursorY += dy[posPtr++];
}
cursorX += fontScale * glyph.getHorizAdvX();
g.setTransform(oldXform);
}
strokeWidthScalar = 1f;
}
protected void renderSysFont(Graphics2D g, java.awt.Font font) throws SVGException
{
float cursorX = 0;
float cursorY = 0;
int posPtr = 1;
FontRenderContext frc = g.getFontRenderContext();
Shape textShape = font.createGlyphVector(frc, text).getOutline(cursorX, cursorY);
renderShape(g, textShape);
Rectangle2D rect = font.getStringBounds(text, frc);
cursorX += (float) rect.getWidth();
}
public Shape getShape()
{
return null;
//return shapeToParent(tspanShape);
}
public Rectangle2D getBoundingBox()
{
return null;
//return boundsToParent(tspanShape.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
*/
public boolean updateTime(double curTime) throws SVGException
{
//Tspan does not change
return false;
}
public String getText()
{
return text;
}
public void setText(String text)
{
this.text = text;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/Use.java 0000664 0000000 0000000 00000016657 12756023445 0024771 0 ustar 00root root 0000000 0000000 /*
* 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()
{
}
public String getTagName()
{
return TAG_NAME;
}
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);
}
public void render(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);
}
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;
}
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
*/
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;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/animation/ 0000775 0000000 0000000 00000000000 12756023445 0025332 5 ustar 00root root 0000000 0000000 svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/animation/AnimTimeParser.jjt 0000664 0000000 0000000 00000016157 12756023445 0030735 0 ustar 00root root 0000000 0000000 /**
* 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;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/animation/Animate.java 0000664 0000000 0000000 00000044453 12756023445 0027565 0 ustar 00root root 0000000 0000000 /*
* 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()
{
}
public String getTagName()
{
return TAG_NAME;
}
public int getDataType()
{
return dataType;
}
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;
}
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;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/animation/AnimateBase.java 0000664 0000000 0000000 00000013053 12756023445 0030350 0 ustar 00root root 0000000 0000000 /*
* 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()
{
}
public void evalParametric(AnimationTimeEval state, double curTime)
{
evalParametric(state, curTime, repeatCount, repeatDur == null ? Double.NaN : repeatDur.evalTime());
}
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; }
}
}
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;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/animation/AnimateColor.java 0000664 0000000 0000000 00000010767 12756023445 0030565 0 ustar 00root root 0000000 0000000 /*
* 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()
{
}
public String getTagName()
{
return TAG_NAME;
}
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));
}
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;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/animation/AnimateColorIface.java 0000664 0000000 0000000 00000003412 12756023445 0031502 0 ustar 00root root 0000000 0000000 /*
* 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);
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/animation/AnimateMotion.java 0000664 0000000 0000000 00000023675 12756023445 0030756 0 ustar 00root root 0000000 0000000 /*
* 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.Iterator;
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 Matcher matchPoint = Pattern.compile("\\s*(\\d+)[^\\d]+(\\d+)\\s*").matcher("");
// 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()
{
}
public String getTagName()
{
return TAG_NAME;
}
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();
matchPoint.reset(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].
*/
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 (Iterator it = bezierSegs.iterator(); it.hasNext();)
{
Bezier bez = (Bezier)it.next();
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;
}
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;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/animation/AnimateTransform.java 0000664 0000000 0000000 00000030671 12756023445 0031456 0 ustar 00root root 0000000 0000000 /*
* 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()
{
}
public String getTagName()
{
return TAG_NAME;
}
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].
*/
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;
}
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;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/animation/AnimateXform.java 0000664 0000000 0000000 00000004337 12756023445 0030576 0 ustar 00root root 0000000 0000000 /*
* 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()
{
}
public void loaderStartElement(SVGLoaderHelper helper, Attributes attrs, SVGElement parent) throws SAXException
{
super.loaderStartElement(helper, attrs, parent);
}
abstract public AffineTransform eval(AffineTransform xform, double interp);
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/animation/AnimationElement.java 0000664 0000000 0000000 00000040125 12756023445 0031430 0 ustar 00root root 0000000 0000000 /*
* 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");
}
}
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
*/
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;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/animation/AnimationTimeEval.java 0000664 0000000 0000000 00000004742 12756023445 0031552 0 ustar 00root root 0000000 0000000 /*
* 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;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/animation/Bezier.java 0000664 0000000 0000000 00000014072 12756023445 0027421 0 ustar 00root root 0000000 0000000 /*
* 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;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/animation/SetSmil.java 0000664 0000000 0000000 00000006310 12756023445 0027555 0 ustar 00root root 0000000 0000000 /*
* 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()
{
}
public String getTagName()
{
return TAG_NAME;
}
public void loaderStartElement(SVGLoaderHelper helper, Attributes attrs, SVGElement parent) throws SAXException
{
//Load style string
super.loaderStartElement(helper, attrs, parent);
toValue = attrs.getValue("to");
}
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;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/animation/TimeBase.java 0000664 0000000 0000000 00000007531 12756023445 0027674 0 ustar 00root root 0000000 0000000 /*
* 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 Matcher matchIndefinite = Pattern.compile("\\s*indefinite\\s*").matcher("");
static final Matcher matchUnitTime = Pattern.compile("\\s*([-+]?((\\d*\\.\\d+)|(\\d+))([-+]?[eE]\\d+)?)\\s*(h|min|s|ms)?\\s*").matcher("");
/*
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)
{
matchIndefinite.reset(text);
if (matchIndefinite.matches()) return new TimeIndefinite();
matchUnitTime.reset(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)
{
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/animation/TimeCompound.java 0000664 0000000 0000000 00000006113 12756023445 0030601 0 ustar 00root root 0000000 0000000 /*
* 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.Iterator;
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);
}
public double evalTime()
{
double agg = 0.0;
for (Iterator it = componentTimes.iterator(); it.hasNext();)
{
TimeBase timeEle = (TimeBase)it.next();
double time = timeEle.evalTime();
agg += time;
}
return agg;
}
public void setParentElement(AnimationElement ele)
{
this.parent = ele;
for (Iterator it = componentTimes.iterator(); it.hasNext();)
{
TimeBase timeEle = (TimeBase)it.next();
timeEle.setParentElement(ele);
}
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/animation/TimeDiscrete.java 0000664 0000000 0000000 00000004131 12756023445 0030555 0 ustar 00root root 0000000 0000000 /*
* 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;
}
public double evalTime()
{
return secs;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/animation/TimeIndefinite.java 0000664 0000000 0000000 00000004025 12756023445 0031073 0 ustar 00root root 0000000 0000000 /*
* 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()
{
}
public double evalTime()
{
return Double.POSITIVE_INFINITY;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/animation/TimeLookup.java 0000664 0000000 0000000 00000005224 12756023445 0030270 0 ustar 00root root 0000000 0000000 /*
* 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;
}
public double evalTime()
{
return 0.0;
}
public void setParentElement(AnimationElement ele)
{
parent = ele;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/animation/TimeSum.java 0000664 0000000 0000000 00000004604 12756023445 0027564 0 ustar 00root root 0000000 0000000 /*
* 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;
}
public double evalTime()
{
return add ? t1.evalTime() + t2.evalTime() : t1.evalTime() - t2.evalTime();
}
public void setParentElement(AnimationElement ele)
{
t1.setParentElement(ele);
t2.setParentElement(ele);
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/animation/TrackBase.java 0000664 0000000 0000000 00000010316 12756023445 0030035 0 ustar 00root root 0000000 0000000 /*
* 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;
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/animation/TrackColor.java 0000664 0000000 0000000 00000007231 12756023445 0030243 0 ustar 00root root 0000000 0000000 /*
* 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.*;
import com.kitfox.svg.xml.*;
/**
* 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);
}
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 (Iterator it = animEvents.iterator(); it.hasNext();)
{
AnimateBase ele = (AnimateBase)it.next();
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;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/animation/TrackDouble.java 0000664 0000000 0000000 00000010606 12756023445 0030377 0 ustar 00root root 0000000 0000000 /*
* 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.*;
import com.kitfox.svg.xml.*;
/**
* 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);
}
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 (Iterator it = animEvents.iterator(); it.hasNext();)
{
Animate ele = (Animate)it.next();
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;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/animation/TrackManager.java 0000664 0000000 0000000 00000012557 12756023445 0030546 0 ustar 00root root 0000000 0000000 /*
* 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;
}
public int hashCode()
{
int hash = name == null ? 0 : name.hashCode();
hash = hash * 97 + type;
return hash;
}
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();
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/animation/TrackMotion.java 0000664 0000000 0000000 00000012175 12756023445 0030435 0 ustar 00root root 0000000 0000000 /*
* 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.*;
import com.kitfox.svg.xml.*;
/**
* 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);
}
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 (Iterator it = animEvents.iterator(); it.hasNext();)
{
AnimateMotion ele = (AnimateMotion)it.next();
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;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/animation/TrackPath.java 0000664 0000000 0000000 00000007541 12756023445 0030065 0 ustar 00root root 0000000 0000000 /*
* 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.awt.geom.*;
import java.util.*;
import com.kitfox.svg.pathcmd.*;
import com.kitfox.svg.*;
import com.kitfox.svg.xml.*;
/**
* 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);
}
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 (Iterator it = animEvents.iterator(); it.hasNext();)
{
AnimateBase ele = (AnimateBase)it.next();
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;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/animation/TrackTransform.java 0000664 0000000 0000000 00000011152 12756023445 0031135 0 ustar 00root root 0000000 0000000 /*
* 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.*;
import com.kitfox.svg.xml.*;
/**
* 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);
}
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 (Iterator it = animEvents.iterator(); it.hasNext();)
{
AnimateXform ele = (AnimateXform)it.next();
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;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/app/ 0000775 0000000 0000000 00000000000 12756023445 0024133 5 ustar 00root root 0000000 0000000 svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/app/MainFrame.form 0000664 0000000 0000000 00000007771 12756023445 0026673 0 ustar 00root root 0000000 0000000
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/app/MainFrame.java 0000664 0000000 0000000 00000013032 12756023445 0026634 0 ustar 00root root 0000000 0000000 /*
* 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()
{
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
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/app/PlayerDialog.form 0000664 0000000 0000000 00000016664 12756023445 0027411 0 ustar 00root root 0000000 0000000
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/app/PlayerDialog.java 0000664 0000000 0000000 00000025411 12756023445 0027355 0 ustar 00root root 0000000 0000000 /*
* 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()
{
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()
{
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()
{
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
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/app/PlayerThread.java 0000664 0000000 0000000 00000010121 12756023445 0027355 0 ustar 00root root 0000000 0000000 /*
* 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 (Iterator it = listeners.iterator(); it.hasNext();)
{
PlayerThreadListener listener = (PlayerThreadListener)it.next();
listener.updateTime(curTime, timeStep, playState);
}
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/app/PlayerThreadListener.java 0000664 0000000 0000000 00000003426 12756023445 0031075 0 ustar 00root root 0000000 0000000 /*
* 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);
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/app/SVGPlayer.form 0000664 0000000 0000000 00000014426 12756023445 0026643 0 ustar 00root root 0000000 0000000
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/app/SVGPlayer.java 0000664 0000000 0000000 00000036047 12756023445 0026624 0 ustar 00root root 0000000 0000000 /*
* 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.Vector;
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("");
public boolean accept(File file)
{
if (file.isDirectory()) return true;
matchLevelFile.reset(file.getName());
return matchLevelFile.matches();
}
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()
{
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++)
{
ArrayList path = (ArrayList)paths.get(i);
System.out.println(pathToString(path));
}
}
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(((SVGElement)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()
{
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
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/app/SVGViewer.form 0000664 0000000 0000000 00000014507 12756023445 0026650 0 ustar 00root root 0000000 0000000
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/app/SVGViewer.java 0000664 0000000 0000000 00000035242 12756023445 0026625 0 ustar 00root root 0000000 0000000 /*
* 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.Iterator;
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("");
public boolean accept(File file)
{
if (file.isDirectory()) return true;
matchLevelFile.reset(file.getName());
return matchLevelFile.matches();
}
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()
{
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()
{
public void mousePressed(java.awt.event.MouseEvent evt)
{
panel_svgAreaMousePressed(evt);
}
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 (Iterator it = pickedElements.iterator(); it.hasNext();)
{
ArrayList path = (ArrayList)it.next();
System.out.print(" Path: ");
for (Iterator it2 = path.iterator(); it2.hasNext();)
{
SVGElement ele = (SVGElement)it2.next();
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
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/app/VersionDialog.form 0000664 0000000 0000000 00000007263 12756023445 0027575 0 ustar 00root root 0000000 0000000
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/app/VersionDialog.java 0000664 0000000 0000000 00000012744 12756023445 0027553 0 ustar 00root root 0000000 0000000 /*
* 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.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.event.*;
import javax.swing.*;
import javax.swing.text.html.*;
/**
*
* @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
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/app/ant/ 0000775 0000000 0000000 00000000000 12756023445 0024715 5 ustar 00root root 0000000 0000000 svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/app/ant/SVGToImageAntTask.java 0000664 0000000 0000000 00000022100 12756023445 0030746 0 ustar 00root root 0000000 0000000 /*
* 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, specifices 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 # notaion 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 antialiasing. Defaults to true.
* interpolation - String describing image interpolation alrogithm. 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 infromation 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.
*/
public void addFileset(FileSet set)
{
filesets.add(set);
}
public void execute()
{
if (verbose) log("Building SVG images");
for (Iterator it = filesets.iterator(); it.hasNext();)
{
FileSet fs = (FileSet)it.next();
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();
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/app/beans/ 0000775 0000000 0000000 00000000000 12756023445 0025223 5 ustar 00root root 0000000 0000000 svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/app/beans/ProportionalLayoutPanel.form 0000664 0000000 0000000 00000004252 12756023445 0032761 0 ustar 00root root 0000000 0000000
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/app/beans/ProportionalLayoutPanel.java 0000664 0000000 0000000 00000010254 12756023445 0032736 0 ustar 00root root 0000000 0000000 /*
* 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 java.util.*;
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();
}
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()
{
public void componentResized(java.awt.event.ComponentEvent evt)
{
formComponentResized(evt);
}
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
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/app/beans/SVGIcon.java 0000664 0000000 0000000 00000036432 12756023445 0027346 0 ustar 00root root 0000000 0000000 /*
* 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);
}
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 getIconHeight()
{
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 getIconWidth()
{
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();
}
/**
* 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
*/
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 = getIconWidth();
final int height = getIconHeight();
// 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
* @return
*/
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);
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/app/beans/SVGPanel.form 0000664 0000000 0000000 00000002360 12756023445 0027530 0 ustar 00root root 0000000 0000000
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/app/beans/SVGPanel.java 0000664 0000000 0000000 00000023042 12756023445 0027506 0 ustar 00root root 0000000 0000000 /*
* 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();
}
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(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
* @return
*/
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
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/app/data/ 0000775 0000000 0000000 00000000000 12756023445 0025044 5 ustar 00root root 0000000 0000000 svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/app/data/Handler.java 0000664 0000000 0000000 00000010012 12756023445 0027256 0 ustar 00root root 0000000 0000000 /*
* 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);
}
}
}
public void connect() throws IOException
{
}
public String getHeaderField(String name)
{
if ("content-type".equals(name))
{
return mime;
}
return super.getHeaderField(name);
}
public InputStream getInputStream() throws IOException
{
return new ByteArrayInputStream(buf);
}
// public Object getContent() throws IOException
// {
// BufferedImage img = ImageIO.read(getInputStream());
// }
}
protected URLConnection openConnection(URL u) throws IOException
{
return new Connection(u);
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/app/data/HandlerFactory.java 0000664 0000000 0000000 00000003676 12756023445 0030630 0 ustar 00root root 0000000 0000000 /*
* 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;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/composite/ 0000775 0000000 0000000 00000000000 12756023445 0025355 5 ustar 00root root 0000000 0000000 svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/composite/AdobeComposite.java 0000664 0000000 0000000 00000005637 12756023445 0031130 0 ustar 00root root 0000000 0000000 /*
* 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 */
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);
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/composite/AdobeCompositeContext.java 0000664 0000000 0000000 00000007504 12756023445 0032470 0 ustar 00root root 0000000 0000000 /*
* 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 */
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() {
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/package-info.java 0000664 0000000 0000000 00000000451 12756023445 0026542 0 ustar 00root root 0000000 0000000 /**
* 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; svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/pathcmd/ 0000775 0000000 0000000 00000000000 12756023445 0024773 5 ustar 00root root 0000000 0000000 svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/pathcmd/Arc.java 0000664 0000000 0000000 00000023123 12756023445 0026344 0 ustar 00root root 0000000 0000000 /*
* 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)
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);
}
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 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);
*/
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;
}
public String toString()
{
return "A " + rx + " " + ry
+ " " + xAxisRot + " " + largeArc
+ " " + sweep
+ " " + x + " " + y;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/pathcmd/BuildHistory.java 0000664 0000000 0000000 00000006225 12756023445 0030264 0 ustar 00root root 0000000 0000000 /*
* 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;
// }
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/pathcmd/Cubic.java 0000664 0000000 0000000 00000006204 12756023445 0026665 0 ustar 00root root 0000000 0000000 /*
* 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() {
}
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)
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);
}
public int getNumKnotsAdded()
{
return 6;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/pathcmd/CubicSmooth.java 0000664 0000000 0000000 00000006237 12756023445 0030065 0 ustar 00root root 0000000 0000000 /*
* 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)
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);
}
public int getNumKnotsAdded()
{
return 6;
}
public String toString()
{
return "S " + k2x + " " + k2y
+ " " + x + " " + y;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/pathcmd/Horizontal.java 0000664 0000000 0000000 00000005120 12756023445 0027765 0 ustar 00root root 0000000 0000000 /*
* 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() {
}
public String toString()
{
return "H " + x;
}
public Horizontal(boolean isRelative, float x) {
super(isRelative);
this.x = x;
}
// public void appendPath(ExtendedGeneralPath path, BuildHistory hist)
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);
}
public int getNumKnotsAdded()
{
return 2;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/pathcmd/LineTo.java 0000664 0000000 0000000 00000005244 12756023445 0027035 0 ustar 00root root 0000000 0000000 /*
* 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)
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);
}
public int getNumKnotsAdded()
{
return 2;
}
public String toString()
{
return "L " + x + " " + y;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/pathcmd/MoveTo.java 0000664 0000000 0000000 00000005333 12756023445 0027053 0 ustar 00root root 0000000 0000000 /*
* 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)
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);
}
public int getNumKnotsAdded()
{
return 2;
}
public String toString()
{
return "M " + x + " " + y;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/pathcmd/PathCommand.java 0000664 0000000 0000000 00000004560 12756023445 0030036 0 ustar 00root root 0000000 0000000 /*
* 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();
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/pathcmd/PathUtil.java 0000664 0000000 0000000 00000006475 12756023445 0027404 0 ustar 00root root 0000000 0000000 /*
* 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
*/
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();
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/pathcmd/Quadratic.java 0000664 0000000 0000000 00000005533 12756023445 0027561 0 ustar 00root root 0000000 0000000 /*
* 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() {
}
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)
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);
}
public int getNumKnotsAdded()
{
return 4;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/pathcmd/QuadraticSmooth.java 0000664 0000000 0000000 00000005724 12756023445 0030755 0 ustar 00root root 0000000 0000000 /*
* 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() {
}
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)
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);
}
public int getNumKnotsAdded()
{
return 4;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/pathcmd/Terminal.java 0000664 0000000 0000000 00000004620 12756023445 0027413 0 ustar 00root root 0000000 0000000 /*
* 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() {
}
public String toString()
{
return "Z";
}
// public void appendPath(ExtendedGeneralPath path, BuildHistory hist)
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);
}
public int getNumKnotsAdded()
{
return 0;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/pathcmd/Vertical.java 0000664 0000000 0000000 00000005104 12756023445 0027407 0 ustar 00root root 0000000 0000000 /*
* 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() {
}
public String toString()
{
return "V " + y;
}
public Vertical(boolean isRelative, float y) {
super(isRelative);
this.y = y;
}
// public void appendPath(ExtendedGeneralPath path, BuildHistory hist)
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);
}
public int getNumKnotsAdded()
{
return 2;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/pattern/ 0000775 0000000 0000000 00000000000 12756023445 0025030 5 ustar 00root root 0000000 0000000 svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/pattern/PatternPaint.java 0000664 0000000 0000000 00000004715 12756023445 0030313 0 ustar 00root root 0000000 0000000 /*
* 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();
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/pattern/PatternPaintContext.java 0000664 0000000 0000000 00000011247 12756023445 0031656 0 ustar 00root root 0000000 0000000 /*
* 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));
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/util/ 0000775 0000000 0000000 00000000000 12756023445 0024330 5 ustar 00root root 0000000 0000000 svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/util/Base64Consts.java 0000664 0000000 0000000 00000003443 12756023445 0027415 0 ustar 00root root 0000000 0000000 /*
* 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+/";
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/util/Base64InputStream.java 0000664 0000000 0000000 00000010035 12756023445 0030412 0 ustar 00root root 0000000 0000000 /*
* 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);
}
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;
}
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;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/util/Base64OutputStream.java 0000664 0000000 0000000 00000006606 12756023445 0030624 0 ustar 00root root 0000000 0000000 /*
* 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);
}
public void close() throws IOException
{
writeBits();
super.close();
}
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;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/util/FontSystem.java 0000664 0000000 0000000 00000007640 12756023445 0027315 0 ustar 00root root 0000000 0000000 /*
* 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.Canvas;
import java.awt.FontMetrics;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphMetrics;
import java.awt.font.GlyphVector;
import java.util.HashMap;
/**
*
* @author kitfox
*/
public class FontSystem extends Font
{
java.awt.Font sysFont;
FontMetrics fm;
HashMap glyphCache = new HashMap();
public FontSystem(String fontFamily, int fontStyle, int fontWeight, int 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, (int) fontSize);
Canvas c = new Canvas();
fm = c.getFontMetrics(sysFont);
FontFace face = new FontFace();
face.setAscent(fm.getAscent());
face.setDescent(fm.getDescent());
face.setUnitsPerEm(fm.charWidth('M'));
setFontFace(face);
}
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((int)gm.getAdvanceX());
glyph.setVertAdvY((int)gm.getAdvanceY());
glyph.setVertOriginX(0);
glyph.setVertOriginY(0);
glyphCache.put(unicode, glyph);
}
return glyph;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/util/TextBuilder.java 0000664 0000000 0000000 00000003262 12756023445 0027431 0 ustar 00root root 0000000 0000000 /*
* 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
{
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/xml/ 0000775 0000000 0000000 00000000000 12756023445 0024153 5 ustar 00root root 0000000 0000000 svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/xml/ColorTable.java 0000664 0000000 0000000 00000030701 12756023445 0027045 0 ustar 00root root 0000000 0000000 /*
* 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) {
Object obj = colorTable.get(name.toLowerCase());
if (obj == null) return null;
return (Color)obj;
}
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;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/xml/NumberWithUnits.java 0000664 0000000 0000000 00000012133 12756023445 0030125 0 ustar 00root root 0000000 0000000 /*
* 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 "%";
}
}
public String toString()
{
return "" + value + unitsAsString(unitType);
}
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;
}
public int hashCode()
{
int hash = 5;
hash = 37 * hash + Float.floatToIntBits(this.value);
hash = 37 * hash + this.unitType;
return hash;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/xml/ReadableXMLElement.java 0000664 0000000 0000000 00000004132 12756023445 0030410 0 ustar 00root root 0000000 0000000 /*
* 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.*;
import java.util.*;
import java.lang.reflect.*;
/**
* @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);
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/xml/StyleAttribute.java 0000664 0000000 0000000 00000022245 12756023445 0030007 0 ustar 00root root 0000000 0000000 /*
* 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 Matcher matchFpNumUnits = Pattern.compile("\\s*([-+]?((\\d*\\.\\d+)|(\\d+))([-+]?[eE]\\d+)?)\\s*(px|cm|mm|in|pc|pt|em|ex)\\s*").matcher("");
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() {
matchFpNumUnits.reset(stringValue);
if (!matchFpNumUnits.matches()) return null;
return matchFpNumUnits.group(6);
}
public NumberWithUnits getNumberWithUnits() {
return XMLParseUtil.parseNumberWithUnits(stringValue);
}
public float getFloatValueWithUnits()
{
NumberWithUnits number = getNumberWithUnits();
return convertUnitsToPixels(number.getUnits(), number.getValue());
}
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);
}
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/xml/StyleSheet.java 0000664 0000000 0000000 00000003301 12756023445 0027104 0 ustar 00root root 0000000 0000000 /*
* 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 null;
}
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;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/xml/StyleSheetRule.java 0000664 0000000 0000000 00000003034 12756023445 0027737 0 ustar 00root root 0000000 0000000 /*
* 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;
}
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;
}
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;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/xml/WritableXMLElement.java 0000664 0000000 0000000 00000004135 12756023445 0030465 0 ustar 00root root 0000000 0000000 /*
* 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.*;
import java.util.*;
import java.lang.reflect.*;
/**
* @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);
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/xml/XMLParseUtil.java 0000664 0000000 0000000 00000057744 12756023445 0027330 0 ustar 00root root 0000000 0000000 /*
* 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 Matcher fpMatch = Pattern.compile("([-+]?((\\d*\\.\\d+)|(\\d+))([eE][+-]?\\d+)?)(\\%|in|cm|mm|pt|pc|px|em|ex)?").matcher("");
static final Matcher intMatch = Pattern.compile("[-+]?\\d+").matcher("");
/** 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 coresponding
* 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)
{
fpMatch.reset(val);
return fpMatch.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;
fpMatch.reset(val);
try
{
if (!fpMatch.find()) return 0;
}
catch (StringIndexOutOfBoundsException e)
{
Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING,
"XMLParseUtil: regex parse problem: '" + val + "'", e);
}
val = fpMatch.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 = fpMatch.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;
fpMatch.reset(list);
LinkedList doubList = new LinkedList();
while (fpMatch.find())
{
String val = fpMatch.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;
fpMatch.reset(val);
if (!fpMatch.find()) return 0f;
val = fpMatch.group(1);
//System.err.println("Parsing " + val);
float retVal = 0f;
try
{
retVal = Float.parseFloat(val);
String units = fpMatch.group(6);
if ("%".equals(units)) retVal /= 100;
}
catch (Exception e)
{}
return retVal;
}
public synchronized static float[] parseFloatList(String list)
{
if (list == null) return null;
fpMatch.reset(list);
LinkedList floatList = new LinkedList();
while (fpMatch.find())
{
String val = fpMatch.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;
intMatch.reset(val);
if (!intMatch.find()) return 0;
val = intMatch.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;
intMatch.reset(list);
LinkedList intList = new LinkedList();
while (intMatch.find())
{
String val = intMatch.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);
URL url;
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++] = ((Integer)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++] = (String)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();
String value = styles[i].substring(colon + 1).trim();
map.put(key, new StyleAttribute(key, value));
}
return map;
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/xml/cpx/ 0000775 0000000 0000000 00000000000 12756023445 0024745 5 ustar 00root root 0000000 0000000 svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/xml/cpx/CPXConsts.java 0000664 0000000 0000000 00000003607 12756023445 0027442 0 ustar 00root root 0000000 0000000 /*
* 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;
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/xml/cpx/CPXInputStream.java 0000664 0000000 0000000 00000024132 12756023445 0030440 0 ustar 00root root 0000000 0000000 /*
* 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 */
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
*/
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
*/
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
*/
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)
*/
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
*/
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
*/
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.
*/
public int available() { return reachedEOF ? 0 : 1; }
/**
* Skips bytes by reading them into a cached buffer
*/
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();
*/ svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/xml/cpx/CPXOutputStream.java 0000664 0000000 0000000 00000014664 12756023445 0030652 0 ustar 00root root 0000000 0000000 /*
* 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 */
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.
*/
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)
*/
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)
*/
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
*/
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
*/
public void close() throws IOException {
deflater.finish();
processAllData();
try {
flush();
} catch (IOException ignored) {
}
out.close();
}
}
svgSalamander-1.1.1/svg-core/src/main/java/com/kitfox/svg/xml/cpx/CPXTest.java 0000664 0000000 0000000 00000007200 12756023445 0027101 0 ustar 00root root 0000000 0000000 /*
* 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();
}
}
svgSalamander-1.1.1/svg-core/src/main/java/xml/ 0000775 0000000 0000000 00000000000 12756023445 0021272 5 ustar 00root root 0000000 0000000 svgSalamander-1.1.1/svg-core/src/main/java/xml/formControls.js 0000664 0000000 0000000 00000001375 12756023445 0024325 0 ustar 00root root 0000000 0000000
/**
* Layout a form control. Must be called to initialize and whenever the
* form's dimensions change.
*/
function pack()
{
}
function moveLabel(name, x, y, width, height)
{
var clipRect = svgDocument.getElementById(name + "-clip-rect");
clipRect.setAttribute("x", x);
clipRect.setAttribute("y", y);
clipRect.setAttribute("width", width);
clipRect.setAttribute("height", height);
var rect = svgDocument.getElementById(name + "-rect");
rect.setAttribute("x", x);
rect.setAttribute("y", y);
rect.setAttribute("width", width);
rect.setAttribute("height", height);
var text = svgDocument.getElementById(name + "-text");
rect.setAttribute("x", x);
rect.setAttribute("y", y);
} svgSalamander-1.1.1/svg-core/src/main/java/xml/postXform.html 0000664 0000000 0000000 00000000650 12756023445 0024162 0 ustar 00root root 0000000 0000000