Java Examples for org.w3c.dom.svg.SVGSVGElement
The following java examples will help you to understand the usage of org.w3c.dom.svg.SVGSVGElement. These source code samples are taken from different open source projects.
Example 1
| Project: batik-master File: JSVGComponent.java View source code |
public void setGraphicsNode(GraphicsNode gn, boolean createDispatcher) {
Dimension2D dim = bridgeContext.getDocumentSize();
Dimension mySz = new Dimension((int) dim.getWidth(), (int) dim.getHeight());
JSVGComponent.this.setMySize(mySz);
SVGSVGElement elt = svgDocument.getRootElement();
prevComponentSize = getSize();
AffineTransform at = calculateViewingTransform(fragmentIdentifier, elt);
CanvasGraphicsNode cgn = getCanvasGraphicsNode(gn);
if (cgn != null) {
cgn.setViewingTransform(at);
}
viewingTransform = null;
initialTransform = new AffineTransform();
setRenderingTransform(initialTransform, false);
jsvgComponentListener.updateMatrix(initialTransform);
addJGVTComponentListener(jsvgComponentListener);
addComponentListener(jsvgComponentListener);
super.setGraphicsNode(gn, createDispatcher);
}Example 2
| Project: signingserver-bb-master File: IconService.java View source code |
private static void changeColor(SVGImage svgImage, String color) {
SVGSVGElement svgElement = (SVGSVGElement) svgImage.getDocument().getDocumentElement();
NodeList paths = svgElement.getElementsByTagName("path");
for (int i = 0; i < paths.getLength(); i++) {
SVGElement element = (SVGElement) paths.item(i);
element.setTrait("fill", color);
}
}Example 3
| Project: delineate-master File: AutotraceSvgOptimizer.java View source code |
public void addBackground(SVGDocument document) {
if (background != null) {
SVGSVGElement root = document.getRootElement();
Element rectangle = document.createElementNS(SVGDOMImplementation.SVG_NAMESPACE_URI, "rect");
rectangle.setAttributeNS(null, "width", root.getWidth().getBaseVal().getValueAsString());
rectangle.setAttributeNS(null, "height", root.getHeight().getBaseVal().getValueAsString());
rectangle.setAttributeNS(null, "fill", '#' + background);
Node firstChild = root.getFirstChild();
root.insertBefore(rectangle, firstChild);
}
}Example 4
| Project: Desktop-master File: SvgViewerFactory.java View source code |
@Override
public void gvtRenderingStarted(final GVTTreeRendererEvent e) {
super.gvtRenderingStarted(e);
final SVGDocument document = getSVGDocument();
final SVGSVGElement rootElement = document.getRootElement();
final SVGLength width = rootElement.getWidth().getBaseVal();
final SVGLength height = rootElement.getHeight().getBaseVal();
float defaultWidth = (float) Math.ceil(width.getValue());
float defaultHeigth = (float) Math.ceil(height.getValue());
if (defaultWidth == 1f && defaultHeigth == 1f) {
defaultWidth = ResourceController.getResourceController().getIntProperty("default_external_component_width", 200);
defaultHeigth = ResourceController.getResourceController().getIntProperty("default_external_component_height", 200);
}
originalSize = new Dimension((int) defaultWidth, (int) defaultHeigth);
if ("".equals(rootElement.getAttributeNS(null, SVGConstants.SVG_VIEW_BOX_ATTRIBUTE))) {
rootElement.setAttributeNS(null, SVGConstants.SVG_VIEW_BOX_ATTRIBUTE, "0 0 " + defaultWidth + " " + defaultHeigth);
}
setSize(originalSize);
removeGVTTreeRendererListener(this);
}Example 5
| Project: Docear-master File: SvgViewerFactory.java View source code |
@Override
public void gvtRenderingStarted(final GVTTreeRendererEvent e) {
super.gvtRenderingStarted(e);
final SVGDocument document = getSVGDocument();
final SVGSVGElement rootElement = document.getRootElement();
final SVGLength width = rootElement.getWidth().getBaseVal();
final SVGLength height = rootElement.getHeight().getBaseVal();
float defaultWidth = (float) Math.ceil(width.getValue());
float defaultHeigth = (float) Math.ceil(height.getValue());
if (defaultWidth == 1f && defaultHeigth == 1f) {
defaultWidth = ResourceController.getResourceController().getIntProperty("default_external_component_width", 200);
defaultHeigth = ResourceController.getResourceController().getIntProperty("default_external_component_height", 200);
}
originalSize = new Dimension((int) defaultWidth, (int) defaultHeigth);
if ("".equals(rootElement.getAttributeNS(null, SVGConstants.SVG_VIEW_BOX_ATTRIBUTE))) {
rootElement.setAttributeNS(null, SVGConstants.SVG_VIEW_BOX_ATTRIBUTE, "0 0 " + defaultWidth + " " + defaultHeigth);
}
setSize(originalSize);
removeGVTTreeRendererListener(this);
}Example 6
| Project: fop-master File: SVGSVGHandler.java View source code |
/** {@inheritDoc} */
public void handleXML(RendererContext context, org.w3c.dom.Document doc, String ns) throws Exception {
if (getNamespace().equals(ns)) {
if (!(doc instanceof SVGDocument)) {
DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();
doc = DOMUtilities.deepCloneDocument(doc, impl);
}
SVGSVGElement svg = ((SVGDocument) doc).getRootElement();
SVGDocument targetDoc = (SVGDocument) context.getProperty(SVG_DOCUMENT);
SVGElement currentPageG = (SVGElement) context.getProperty(SVG_PAGE_G);
Element view = targetDoc.createElementNS(getNamespace(), "svg");
Node newsvg = targetDoc.importNode(svg, true);
//view.setAttributeNS(null, "viewBox", "0 0 ");
int xpos = ((Integer) context.getProperty(XPOS)).intValue();
int ypos = ((Integer) context.getProperty(YPOS)).intValue();
view.setAttributeNS(null, "x", "" + xpos / 1000f);
view.setAttributeNS(null, "y", "" + ypos / 1000f);
// this fixes a problem where the xmlns is repeated sometimes
Element ele = (Element) newsvg;
ele.setAttributeNS(XMLSupport.XMLNS_NAMESPACE_URI, "xmlns", getNamespace());
if (ele.hasAttributeNS(null, "xmlns")) {
ele.removeAttributeNS(null, "xmlns");
}
view.appendChild(newsvg);
currentPageG.appendChild(view);
}
}Example 7
| Project: android-drawables-maven-plugin-master File: RasterizeSVGMojo.java View source code |
/*
* (non-Javadoc)
*
* @see org.apache.maven.plugin.Mojo#execute()
*/
public void execute() throws MojoExecutionException, MojoFailureException {
if (this.densities.size() == 0) {
Density.defaults(this.densities);
}
ImageTranscoder transcoder = null;
try {
transcoder = this.transcoderFactory.create(this.rasterizedType);
} catch (TranscoderFactoryException e) {
throw new MojoExecutionException("Unable to create transcoder", e);
}
Map<String, File> svgsToProcess = getSVGsToProcess(this.svgDirectory);
for (Entry<String, File> svgToProcess : svgsToProcess.entrySet()) {
try {
String inputURI = svgToProcess.getValue().toURI().toString();
Document svgDoc = this.svgDocFactory.createDocument(inputURI);
SVGSVGElement svgDocElement = (SVGSVGElement) svgDoc.getDocumentElement();
float width = svgDocElement.getWidth().getBaseVal().getValue();
for (Density density : this.densities) {
getLog().debug("Rasterizing " + svgToProcess.getValue() + " -> " + density.getName() + "/" + svgToProcess.getKey() + "." + this.rasterizedType + " [" + density.getScaleFactor() + "]");
File outputDir = createDirectory(this.targetDir, density.getName());
File outputFile = new File(outputDir, svgToProcess.getKey() + "." + this.rasterizedType);
outputFile.createNewFile();
OutputStream os = new FileOutputStream(outputFile);
TranscoderInput input = new TranscoderInput(svgDoc);
TranscoderOutput output = new TranscoderOutput(os);
transcoder.addTranscodingHint(ImageTranscoder.KEY_WIDTH, new Float(Math.ceil(density.getScaleFactor() * width)));
transcoder.transcode(input, output);
}
} catch (IOException e) {
throw new MojoFailureException("Unable to rasterize " + svgToProcess.getValue().getAbsolutePath(), e);
} catch (TranscoderException e) {
throw new MojoFailureException("Unable to rasterize " + svgToProcess.getValue().getAbsolutePath(), e);
}
}
}Example 8
| Project: gmf-runtime-master File: ImageTranscoderEx.java View source code |
/** * calculateSizeTransform * Calculates the transformation matrix that is applied during the render operation. Specifically, * the transformation for changing the size of the rendered data. * * @param svgRoot SVGSVGElement root element of the SVG tree. * @param gvtRoot GraphicsNode graphic node root * @param uri String of the SVG document URI * @param docWidth float width values of the original vector. * @param docHeight float height values of the original vector. * @param newWidth float width values of the rendered image. * @param newHeight float height values of the rendered image. * @return AffineTransform object that represents the size transformation to take place. * @throws TranscoderException thrown if a BridgeException occurs when building the root object. */ protected AffineTransform calculateSizeTransform(SVGSVGElement svgRoot, GraphicsNode gvtRoot, String uri, float docWidth, float docHeight, float newWidth, float newHeight) throws TranscoderException { AffineTransform Px; String ref = null; try { //$NON-NLS-1$ ref = new URL(uri == null ? "" : uri).getRef(); } catch (MalformedURLException ex) { } boolean maintainAspectRatio = true; if (hints.containsKey(KEY_MAINTAIN_ASPECT_RATIO)) { maintainAspectRatio = ((Boolean) hints.get(KEY_MAINTAIN_ASPECT_RATIO)).booleanValue(); } if (maintainAspectRatio) { try { Px = ViewBox.getViewTransform(ref, svgRoot, newWidth, newHeight); } catch (BridgeException ex) { throw new TranscoderException(ex); } if (Px.isIdentity() && (newWidth != docWidth || newHeight != docHeight)) { // The document has no viewBox, we need to resize it by hand. // we want to keep the document size ratio float xscale = newWidth / docWidth; float yscale = newHeight / docHeight; if (docHeight / docWidth > newHeight / newWidth) { xscale = yscale; } else { yscale = xscale; } Px = AffineTransform.getScaleInstance(xscale, yscale); } } else { float xscale = newWidth / docWidth; float yscale = newHeight / docHeight; Px = AffineTransform.getScaleInstance(xscale, yscale); } // take the AOI into account if any if (hints.containsKey(KEY_AOI)) { Rectangle2D aoi = (Rectangle2D) hints.get(KEY_AOI); // transform the AOI into the image's coordinate system aoi = Px.createTransformedShape(aoi).getBounds2D(); AffineTransform Mx = new AffineTransform(); double sx = newWidth / aoi.getWidth(); double sy = newHeight / aoi.getHeight(); Mx.scale(sx, sy); double tx = -aoi.getX(); double ty = -aoi.getY(); Mx.translate(tx, ty); // take the AOI transformation matrix into account // we apply first the preserveAspectRatio matrix Px.preConcatenate(Mx); } CanvasGraphicsNode cgn = getCanvasGraphicsNode(gvtRoot); if (cgn != null) { cgn.setViewingTransform(Px); curTxf = new AffineTransform(); } else { curTxf = Px; } return curTxf; }
Example 9
| Project: jDip-master File: XJSVGCanvas.java View source code |
public void gvtRenderingCompleted(GVTTreeRendererEvent e) {
AffineTransform iat = getInitialTransform();
SVGSVGElement elt = getSVGDocument().getRootElement();
if (// very very defensive... but iat null check is important
iat != null || elt == null) {
// rescale viewbox transform to reflect viewbox size
// size of the canvas' scrolling container (don't include scroll bars)
Dimension vbSize = mapPanel.getScrollerSize();
CanvasGraphicsNode cgn = getCanvasGraphicsNode();
// ViewBox.getViewTransform is essential for calculating the correct transform,
// AND accounting for any viewBox attribute of the root SVG element, if present.
AffineTransform vt = ViewBox.getViewTransform(getFragmentIdentifier(), elt, vbSize.width, vbSize.height);
cgn.setViewingTransform(vt);
// set rendering transform to 'unscaled'
AffineTransform t = AffineTransform.getScaleInstance(1, 1);
XJSVGCanvas.super.setRenderingTransform(t);
}
}Example 10
| Project: LiveFootball-master File: SVGImage.java View source code |
private SVGSVGElement getSVGElement() { SVGSVGElement retVal = null; Document dom = im.getDocument(); retVal = (SVGSVGElement) dom.getElementById(this.getClass().getName() + id); if (retVal == null) { retVal = (SVGSVGElement) dom.createElementNS(SVG_NAMESPACE, "svg"); id = idCounter++; retVal.setId(this.getClass().getName() + id); } return retVal; }
Example 11
| Project: lwuit-master File: SVGImplementation.java View source code |
private SVGSVGElement getSVGElement(SVGImage im) { SVGSVGElement retVal = null; Document dom = im.getDocument(); retVal = (SVGSVGElement) dom.getElementById(this.getClass().getName() + id); if (retVal == null) { retVal = (SVGSVGElement) dom.createElementNS(SVG_NAMESPACE, "svg"); id = idCounter++; retVal.setId(this.getClass().getName() + id); } return retVal; }
Example 12
| Project: FractDim-master File: FractalPanel.java View source code |
public void updateDocument(FractalDocument doc) {
canvas.addGVTTreeRendererListener(new GVTTreeRendererAdapter() {
@Override
public void gvtRenderingCompleted(GVTTreeRendererEvent e) {
synchronized (lock) {
updateManagerIsReady = true;
for (Iterator<Runnable> it = temporaryRunnableQueue.iterator(); it.hasNext(); ) {
Runnable next = it.next();
canvas.getUpdateManager().getUpdateRunnableQueue().invokeLater(next);
it.remove();
}
}
}
});
rootBoundingBox = doc.getMetadata().getBoundingBox();
currentBoundingBox = rootBoundingBox;
// put any existing group elements inside a known root group with ZIndex Integer.MAX_VALUE
SVGDocument document = doc.getSvgDoc();
SVGElementCreator creator = new SVGElementCreator(document);
SVGSVGElement root = document.getRootElement();
Element group = creator.createGroup();
NodeList children = root.getChildNodes();
int childCount = children.getLength();
List<Node> nodesToAppendToGroup = new ArrayList<Node>();
for (int i = 0; i < childCount; i++) {
Node child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE) {
Element childEl = (Element) child;
if ("g".equals(childEl.getTagName())) {
nodesToAppendToGroup.add(childEl);
}
}
}
for (Node node : nodesToAppendToGroup) {
group.appendChild(root.removeChild(node));
}
root.appendChild(group);
zIndexMap.put(group.getAttributeNS(null, "id"), Integer.MAX_VALUE);
canvas.setSVGDocument(document);
}Example 13
| Project: JDE-Samples-master File: SVGMapScreen.java View source code |
/**
* Initialize the SVG Map and the remaining screen components.
*/
private void initializeUI() {
// Initialize a FlowFieldManager to have the checkboxes layed out.
_checkboxManager = new FlowFieldManager(Manager.HORIZONTAL_SCROLL);
// Add the SVG Map to a custom manager to handle its behaviour as a
// custom
// togglable field.
_mapManager = new SVGMapManager();
add(_mapManager);
_svgField = (Field) _animator.getTargetComponent();
_mapManager.add(_svgField);
// Initialize a hashtable for our check boxes.
_checkboxes = new Hashtable(3);
// Populates the hashtable, associates listeners with the checkbox
final CheckboxField roadsCheckBox = new CheckboxField("Roads ", true);
final SVGElement roadsGroup = (SVGElement) _document.getElementById("roads");
_checkboxes.put(roadsCheckBox, roadsGroup);
final CheckboxField railsCheckBox = new CheckboxField("Railways ", true);
final SVGElement railsGroup = (SVGElement) _document.getElementById("railways");
_checkboxes.put(railsCheckBox, railsGroup);
final CheckboxField interestsCheckBox = new CheckboxField("Points of interest ", true);
final SVGElement interestsGroup = (SVGElement) _document.getElementById("interests");
_checkboxes.put(interestsCheckBox, interestsGroup);
final CheckboxField restaurantCheckBox = new CheckboxField("Restaurants ", true);
final SVGElement restaurantGroup = (SVGElement) _document.getElementById("restaurants");
_checkboxes.put(restaurantCheckBox, restaurantGroup);
// Set this class as the handler of the change listeners.
roadsCheckBox.setChangeListener(this);
railsCheckBox.setChangeListener(this);
restaurantCheckBox.setChangeListener(this);
interestsCheckBox.setChangeListener(this);
// Adds the checkboxes to the layout manager.
_checkboxManager.add(roadsCheckBox);
_checkboxManager.add(railsCheckBox);
_checkboxManager.add(restaurantCheckBox);
_checkboxManager.add(interestsCheckBox);
// Adds the layout manager to the screen.
add(_checkboxManager);
// Obtain the root element and the view box settings.
_svg = (SVGSVGElement) _document.getDocumentElement();
_svgViewBox = _svg.getRectTrait("viewBox");
// Get the border element.
_viewportElement = (SVGElement) _document.getElementById("viewport");
_viewportElement.addEventListener("DOMActivate", this, false);
}Example 14
| Project: geolatte-maprenderer-master File: ExternalGraphicsRepository.java View source code |
private BufferedImage transCodeSVG(SVGDocument svg, float size) {
if (size < 0) {
size = DEFAULT_SIZE;
}
SVGTranscoder transcoder = new SVGTranscoder();
SVGSVGElement svgRootElement = svg.getRootElement();
float svgWidth = svgRootElement.getWidth().getBaseVal().getValue();
float svgHeight = svgRootElement.getHeight().getBaseVal().getValue();
// float aspectRatio = svgWidth/svgHeight;
// int height = Math.round(size);
// int width = (int)(aspectRatio * height);
Dimension dim = getWidthAndHeight(svgWidth, svgHeight, size);
return transcoder.transcode(svg, dim.width, dim.height);
}Example 15
| Project: navigps-master File: NaviRootWindow.java View source code |
@Override
public void actionPerformed(ActionEvent e) {
SVGDocument doc = getSVGCanvas().getSVGDocument();
if (doc != null) {
SVGSVGElement el = doc.getRootElement();
String viewBoxStr = el.getAttributeNS(null, SVGConstants.SVG_VIEW_BOX_ATTRIBUTE);
float[] rect = ViewBox.parseViewBoxAttribute(el, viewBoxStr, null);
Rectangle2D rect2d = new Rectangle2D.Float(rect[0], rect[1], rect[2], rect[3]);
GraphicsNode gn = getSVGCanvas().getGraphicsNode();
Rectangle2D bounds = gn.getBounds();
CanvasGraphicsNode cgn = getSVGCanvas().getCanvasGraphicsNode();
String msg = "-------- Transforms SVG Document --------\n" + "\t" + getClass().getName() + "\n" + "ViewingTransform\t" + getSVGCanvas().getViewingTransform() + "\n" + "ViewBoxTransform\t" + getSVGCanvas().getViewBoxTransform() + "\n" + "RenderingTransform\t" + getSVGCanvas().getRenderingTransform() + "\n" + "PaintingTransform\t" + getSVGCanvas().getPaintingTransform() + "\n" + "InitialTransform\t" + getSVGCanvas().getInitialTransform() + "\n" + "Visible Rect\t" + getSVGCanvas().getVisibleRect() + "\n" + "ViewBox Rect\t" + rect2d + "\t" + bounds + "\n" + "-------- Transform Graphics Nood -------" + "\n" + "PositionTransform\t" + cgn.getPositionTransform() + "\n" + "ViewingTransform\t" + cgn.getViewingTransform() + "\n" + "GlobalTransform\t" + cgn.getGlobalTransform() + "\n" + "InverseTransform\t" + cgn.getInverseTransform() + "\n" + "Transform\t" + cgn.getTransform() + "\n" + "----------------------------------------";
getVerboseStream().outputVerboseStream(msg);
}
}Example 16
| Project: MetaDND-master File: JSVGScrollPane.java View source code |
public void documentLoadingCompleted(SVGDocumentLoaderEvent e) {
NodeEventTarget root = (NodeEventTarget) e.getSVGDocument().getRootElement();
root.addEventListenerNS(XMLConstants.XML_EVENTS_NAMESPACE_URI, SVGConstants.SVG_SVGZOOM_EVENT_TYPE, new EventListener() {
public void handleEvent(Event evt) {
if (!(evt.getTarget() instanceof SVGSVGElement))
return;
// assert(evt.getType() ==
// SVGConstants.SVG_SVGZOOM_EVENT_TYPE);
SVGSVGElement svg = (SVGSVGElement) evt.getTarget();
scaleChange(svg.getCurrentScale());
}
}, false, null);
}Example 17
| Project: PSD-master File: SVGImageReader.java View source code |
private BufferedImage readImage() throws TranscoderException {
init();
if (abortRequested()) {
processReadAborted();
return null;
}
processImageProgress(10f);
// Hacky workaround below...
if (gvtRoot == null) {
// Try to reparse, if we had no URI last time...
if (uri != transcoderInput.getURI()) {
try {
context.dispose();
document.setURLObject(new URL(transcoderInput.getURI()));
transcode(document, transcoderInput.getURI(), null);
} catch (MalformedURLException ignore) {
}
}
if (gvtRoot == null) {
throw exception;
}
}
ctx = context;
// /Hacky
if (abortRequested()) {
processReadAborted();
return null;
}
processImageProgress(20f);
// ----
SVGSVGElement root = document.getRootElement();
// ----
// ----
setImageSize(defaultWidth, defaultHeight);
if (abortRequested()) {
processReadAborted();
return null;
}
processImageProgress(40f);
// compute the preserveAspectRatio matrix
AffineTransform Px;
String ref = new ParsedURL(uri).getRef();
try {
Px = ViewBox.getViewTransform(ref, root, width, height, null);
} catch (BridgeException ex) {
throw new TranscoderException(ex);
}
if (Px.isIdentity() && (width != defaultWidth || height != defaultHeight)) {
// The document has no viewBox, we need to resize it by hand.
// we want to keep the document size ratio
float xscale, yscale;
xscale = width / defaultWidth;
yscale = height / defaultHeight;
float scale = Math.min(xscale, yscale);
Px = AffineTransform.getScaleInstance(scale, scale);
}
// take the AOI into account if any
if (hints.containsKey(KEY_AOI)) {
Rectangle2D aoi = (Rectangle2D) hints.get(KEY_AOI);
// transform the AOI into the image's coordinate system
aoi = Px.createTransformedShape(aoi).getBounds2D();
AffineTransform Mx = new AffineTransform();
double sx = width / aoi.getWidth();
double sy = height / aoi.getHeight();
Mx.scale(sx, sy);
double tx = -aoi.getX();
double ty = -aoi.getY();
Mx.translate(tx, ty);
// take the AOI transformation matrix into account
// we apply first the preserveAspectRatio matrix
Px.preConcatenate(Mx);
curAOI = aoi;
} else {
curAOI = new Rectangle2D.Float(0, 0, width, height);
}
if (abortRequested()) {
processReadAborted();
return null;
}
processImageProgress(50f);
CanvasGraphicsNode cgn = getCanvasGraphicsNode(gvtRoot);
if (cgn != null) {
cgn.setViewingTransform(Px);
curTxf = new AffineTransform();
} else {
curTxf = Px;
}
try {
// dispatch an 'onload' event if needed
if (ctx.isDynamic()) {
BaseScriptingEnvironment se;
se = new BaseScriptingEnvironment(ctx);
se.loadScripts();
se.dispatchSVGLoadEvent();
}
} catch (BridgeException ex) {
throw new TranscoderException(ex);
}
this.root = gvtRoot;
// ----
// NOTE: The code below is copied and pasted from the Batik
// ImageTranscoder class' transcode() method:
// prepare the image to be painted
int w = (int) (width + 0.5);
int h = (int) (height + 0.5);
// paint the SVG document using the bridge package
// create the appropriate renderer
ImageRendererFactory rendFactory = new ConcreteImageRendererFactory();
// ImageRenderer renderer = rendFactory.createDynamicImageRenderer();
ImageRenderer renderer = rendFactory.createStaticImageRenderer();
renderer.updateOffScreen(w, h);
renderer.setTransform(curTxf);
renderer.setTree(this.root);
// We're done with it...
this.root = null;
if (abortRequested()) {
processReadAborted();
return null;
}
processImageProgress(75f);
try {
// now we are sure that the aoi is the image size
Shape raoi = new Rectangle2D.Float(0, 0, width, height);
// Warning: the renderer's AOI must be in user space
renderer.repaint(curTxf.createInverse().createTransformedShape(raoi));
// NOTE: repaint above cause nullpointer exception with fonts..???
BufferedImage rend = renderer.getOffScreen();
// We're done with it...
renderer = null;
BufferedImage dest = createImage(w, h);
Graphics2D g2d = GraphicsUtil.createGraphics(dest);
try {
if (hints.containsKey(ImageTranscoder.KEY_BACKGROUND_COLOR)) {
Paint bgcolor = (Paint) hints.get(ImageTranscoder.KEY_BACKGROUND_COLOR);
g2d.setComposite(AlphaComposite.SrcOver);
g2d.setPaint(bgcolor);
g2d.fillRect(0, 0, w, h);
}
if (rend != null) {
// might be null if the svg document is empty
g2d.drawRenderedImage(rend, new AffineTransform());
}
} finally {
if (g2d != null) {
g2d.dispose();
}
}
if (abortRequested()) {
processReadAborted();
return null;
}
processImageProgress(99f);
return dest;
} catch (Exception ex) {
TranscoderException exception = new TranscoderException(ex.getMessage());
exception.initCause(ex);
throw exception;
} finally {
if (context != null) {
context.dispose();
}
}
}Example 18
| Project: TwelveMonkeys-master File: SVGImageReader.java View source code |
private BufferedImage readImage() throws TranscoderException {
init();
if (abortRequested()) {
processReadAborted();
return null;
}
processImageProgress(10f);
// Hacky workaround below...
if (gvtRoot == null) {
// Try to reparse, if we had no URI last time...
if (uri != transcoderInput.getURI()) {
try {
context.dispose();
document.setURLObject(new URL(transcoderInput.getURI()));
transcode(document, transcoderInput.getURI(), null);
} catch (MalformedURLException ignore) {
}
}
if (gvtRoot == null) {
throw exception;
}
}
ctx = context;
// /Hacky
if (abortRequested()) {
processReadAborted();
return null;
}
processImageProgress(20f);
// ----
SVGSVGElement root = document.getRootElement();
// ----
// ----
setImageSize(defaultWidth, defaultHeight);
if (abortRequested()) {
processReadAborted();
return null;
}
processImageProgress(40f);
// compute the preserveAspectRatio matrix
AffineTransform Px;
String ref = new ParsedURL(uri).getRef();
try {
Px = ViewBox.getViewTransform(ref, root, width, height, null);
} catch (BridgeException ex) {
throw new TranscoderException(ex);
}
if (Px.isIdentity() && (width != defaultWidth || height != defaultHeight)) {
// The document has no viewBox, we need to resize it by hand.
// we want to keep the document size ratio
float xscale, yscale;
xscale = width / defaultWidth;
yscale = height / defaultHeight;
float scale = Math.min(xscale, yscale);
Px = AffineTransform.getScaleInstance(scale, scale);
}
// take the AOI into account if any
if (hints.containsKey(KEY_AOI)) {
Rectangle2D aoi = (Rectangle2D) hints.get(KEY_AOI);
// transform the AOI into the image's coordinate system
aoi = Px.createTransformedShape(aoi).getBounds2D();
AffineTransform Mx = new AffineTransform();
double sx = width / aoi.getWidth();
double sy = height / aoi.getHeight();
Mx.scale(sx, sy);
double tx = -aoi.getX();
double ty = -aoi.getY();
Mx.translate(tx, ty);
// take the AOI transformation matrix into account
// we apply first the preserveAspectRatio matrix
Px.preConcatenate(Mx);
curAOI = aoi;
} else {
curAOI = new Rectangle2D.Float(0, 0, width, height);
}
if (abortRequested()) {
processReadAborted();
return null;
}
processImageProgress(50f);
CanvasGraphicsNode cgn = getCanvasGraphicsNode(gvtRoot);
if (cgn != null) {
cgn.setViewingTransform(Px);
curTxf = new AffineTransform();
} else {
curTxf = Px;
}
try {
// dispatch an 'onload' event if needed
if (ctx.isDynamic()) {
BaseScriptingEnvironment se;
se = new BaseScriptingEnvironment(ctx);
se.loadScripts();
se.dispatchSVGLoadEvent();
}
} catch (BridgeException ex) {
throw new TranscoderException(ex);
}
this.root = gvtRoot;
// ----
// NOTE: The code below is copied and pasted from the Batik
// ImageTranscoder class' transcode() method:
// prepare the image to be painted
int w = (int) (width + 0.5);
int h = (int) (height + 0.5);
// paint the SVG document using the bridge package
// create the appropriate renderer
ImageRendererFactory rendFactory = new ConcreteImageRendererFactory();
// ImageRenderer renderer = rendFactory.createDynamicImageRenderer();
ImageRenderer renderer = rendFactory.createStaticImageRenderer();
renderer.updateOffScreen(w, h);
renderer.setTransform(curTxf);
renderer.setTree(this.root);
// We're done with it...
this.root = null;
if (abortRequested()) {
processReadAborted();
return null;
}
processImageProgress(75f);
try {
// now we are sure that the aoi is the image size
Shape raoi = new Rectangle2D.Float(0, 0, width, height);
// Warning: the renderer's AOI must be in user space
renderer.repaint(curTxf.createInverse().createTransformedShape(raoi));
// NOTE: repaint above cause nullpointer exception with fonts..???
BufferedImage rend = renderer.getOffScreen();
// We're done with it...
renderer = null;
BufferedImage dest = createImage(w, h);
Graphics2D g2d = GraphicsUtil.createGraphics(dest);
try {
if (hints.containsKey(ImageTranscoder.KEY_BACKGROUND_COLOR)) {
Paint bgcolor = (Paint) hints.get(ImageTranscoder.KEY_BACKGROUND_COLOR);
g2d.setComposite(AlphaComposite.SrcOver);
g2d.setPaint(bgcolor);
g2d.fillRect(0, 0, w, h);
}
if (rend != null) {
// might be null if the svg document is empty
g2d.drawRenderedImage(rend, new AffineTransform());
}
} finally {
if (g2d != null) {
g2d.dispose();
}
}
if (abortRequested()) {
processReadAborted();
return null;
}
processImageProgress(99f);
return dest;
} catch (Exception ex) {
TranscoderException exception = new TranscoderException(ex.getMessage());
exception.initCause(ex);
throw exception;
} finally {
if (context != null) {
context.dispose();
}
}
}Example 19
| Project: phoneme-qtopia-master File: SVG.java View source code |
// ========================================================================
/**
*
*/
public void setCurrentScale(final float value) throws DOMException {
if (value == 0) {
throw new DOMException(DOMException.INVALID_ACCESS_ERR, Messages.formatMessage(Messages.ERROR_INVALID_PARAMETER_VALUE, new String[] { "SVGSVGElement", "setCurrentScale", "value", Float.toString(value) }));
} else {
currentScale = value;
applyUserTransform();
}
}Example 20
| Project: GestureSound-master File: SVGLoader.java View source code |
/**
* Traverse svg doc.
*
* @param node the node
* @param comps the comps
*/
private void traverseSVGDoc(Node node, ArrayList<MTComponent> comps) {
logger.debug("Traversing: " + node.getNodeName());
//Damit transformationen konsistent sind muss
//jedes tag, daß eine transform attribut hat
//behandelt werden!
//Default
currentLocalTransformMatrix = new Matrix();
//If there is a TRANSFORM attribute parse that and set the
//current transformation matrix to be used with the svg components created after
NamedNodeMap atts = node.getAttributes();
if (atts != null) {
for (int i = 0; i < atts.getLength(); i++) {
Node att = atts.item(i);
if (att.getNodeName().equals(SVG_TRANSFORM_ATTRIBUTE)) {
CustomTransformHandler transFormHandler = new CustomTransformHandler();
TransformListParser transFormListParser = new TransformListParser();
transFormListParser.setTransformListHandler(transFormHandler);
transFormListParser.parse(att.getNodeValue());
//Overwrite current default matrix if the element has its own
//transform defined, will be used at gfx obj creation
currentLocalTransformMatrix = transFormHandler.getResultMatrix();
}
}
}
//For opacity inheritance
if (node instanceof SVGGraphicsElement) {
SVGGraphicsElement svgGfx = (SVGGraphicsElement) node;
//Handle inherited opacity settings
float opac = queryPrimitiveFloatValue(svgGfx, "opacity", 1f);
opacityStack.push(opac *= opacityStack.peek().floatValue());
}
// if G (GROUP) element, add all children to this element
if (node instanceof SVGOMGElement || node instanceof SVGSVGElement || node instanceof SVGOMSVGElement) {
// SVGOMGElement gElem = (SVGOMGElement)node;
SVGElement gElem = (SVGElement) node;
MTComponent group = new MTComponent(pa);
group.setName(gElem.getTagName());
// Element viewPort = gElem.getViewportElement();
// logger.debug("Viewport " + viewPort.getNodeName());
//Set the <g> group to composite, meaning that it will
//be returned at picking, when one of the children gets picked
group.setComposite(true);
group.setLocalMatrix(currentLocalTransformMatrix);
//(to honor the viewBox and the width/height attributes
if (node instanceof SVGOMSVGElement) {
SVGOMSVGElement svgGom = ((SVGOMSVGElement) node);
Element viewPort = svgGom.getViewportElement();
if (viewPort != null)
logger.debug("Viewport " + viewPort.getNodeName());
// SVGMatrix mat = svgGom.getScreenCTM();
SVGAnimatedLength widthA = svgGom.getWidth();
SVGAnimatedLength heightA = svgGom.getHeight();
SVGLength w = widthA.getBaseVal();
float width = w.getValue();
SVGLength h = heightA.getBaseVal();
float height = h.getValue();
logger.debug("-> SVG Width: " + width + " Height: " + height);
SVGMatrix mat = svgGom.getCTM();
//is assumed by batik -> things may get scaled too small
if (!(width == 1 && height == 1)) {
currentLocalTransformMatrix = new Matrix(mat.getA(), mat.getC(), 0, mat.getE(), mat.getB(), mat.getD(), 0, mat.getF(), 0, 0, 1, 0, 0, 0, 0, 1);
//logger.debug("Matrix: " + currentLocalTransformMatrix);
group.setLocalMatrix(currentLocalTransformMatrix);
}
}
//Make the group pickable and manipulatable
group.setPickable(true);
group.registerInputProcessor(new DragProcessor(pa));
group.setGestureAllowance(DragProcessor.class, true);
group.addGestureListener(DragProcessor.class, (IGestureEventListener) defaultDragAction);
group.registerInputProcessor(new RotateProcessor(pa));
group.addGestureListener(RotateProcessor.class, defaultRotateAction);
group.registerInputProcessor(new ScaleProcessor(pa));
group.addGestureListener(ScaleProcessor.class, defaultScaleAction);
ArrayList<MTComponent> groupChildren = new ArrayList<MTComponent>();
//Traverse the children and add them to a new arraylist
traverseChildren(gElem, groupChildren);
MTComponent[] childComps = (MTComponent[]) groupChildren.toArray(new MTComponent[groupChildren.size()]);
//Add the children to the group
group.addChildren(childComps);
//Add the group to the arraylist of the parent
comps.add(group);
} else //If NOT GROUP
{
if (node instanceof SVGGraphicsElement) {
SVGGraphicsElement svgGfxElem = (SVGGraphicsElement) node;
//IF node isnt a group node just add it to the passed in comps arraylist
try {
//Create a component from the graphicsnode and add it to the parents arraylist
MTComponent liveComponent = handleGraphicsNode(svgGfxElem);
if (liveComponent != null) {
comps.add(liveComponent);
}
} catch (Exception e) {
logger.error("Error handling svg node: " + svgGfxElem.getTagName());
e.printStackTrace();
}
}
//FIXME IMPLEMENT
if (node instanceof SVGOMTSpanElement) {
SVGOMTSpanElement tSpanElement = (SVGOMTSpanElement) node;
}
//FIXME TEST
if (node instanceof SVGOMTextElement) {
boolean useVectorFont = false;
SVGOMTextElement textElement = (SVGOMTextElement) node;
//Get <text> position values (can be a list)
List<Float> xValues = getSVGLengthListAsFloat(textElement.getX().getBaseVal());
List<Float> yValues = getSVGLengthListAsFloat(textElement.getY().getBaseVal());
// /*//Not used
String textContent = TextUtilities.getElementContent(textElement);
textContent = textContent.replaceAll("\\n", "");
textContent = textContent.trim();
/*
//TODO USE?
textElement.getTextLength();
textElement.getRotate();
*/
if (textElement.getSVGContext() instanceof SVGTextElementBridge) {
SVGTextElementBridge b = (SVGTextElementBridge) textElement.getSVGContext();
GraphicsNode gr = b.createGraphicsNode(ctx, textElement);
TextNode tNode = (TextNode) gr;
b.buildGraphicsNode(ctx, textElement, tNode);
List<?> textRuns = tNode.getTextRuns();
logger.debug("Text runs: " + textRuns);
//Get font size
float fontSize = b.getFontSize();
logger.debug("Text:" + " x:" + xValues.get(0) + " y:" + yValues.get(0) + " FontSize: " + fontSize + " Text: '" + textContent + "'");
//Get font FILL
Value fillOpacValue = CSSUtilities.getComputedStyle(textElement, SVGCSSEngine.FILL_OPACITY_INDEX);
float computedfillOpac = PaintServer.convertOpacity(fillOpacValue);
Value fillIndexValue = CSSUtilities.getComputedStyle(textElement, SVGCSSEngine.FILL_INDEX);
Object fill = SVGLoader.getFillOrStroke(textElement, fillIndexValue, computedfillOpac, ctx);
MTColor fillColor = new MTColor(150, 150, 150, 255);
if (fill instanceof java.awt.Color) {
java.awt.Color color = (Color) fill;
fillColor.setColor(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha());
}
//Get STROKE
// Stroke Opacity \\
Value strokeOpacValue = CSSUtilities.getComputedStyle(textElement, SVGCSSEngine.STROKE_OPACITY_INDEX);
float computedStrokeOpacity = PaintServer.convertOpacity(strokeOpacValue);
// Stroke java.awt.Color \\
Value strokeIndexValue = CSSUtilities.getComputedStyle(textElement, SVGCSSEngine.STROKE_INDEX);
Object stroke = SVGLoader.getFillOrStroke(textElement, strokeIndexValue, computedStrokeOpacity, ctx);
MTColor strokeColor = new MTColor(fillColor.getR(), fillColor.getG(), fillColor.getB(), fillColor.getAlpha());
if (stroke instanceof java.awt.Color) {
java.awt.Color color = (Color) stroke;
strokeColor.setColor(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha());
}
//Get the font family
Value fontFamilyValue = CSSUtilities.getComputedStyle(textElement, SVGCSSEngine.FONT_FAMILY_INDEX);
String //DEFAULT
fontFamily = //DEFAULT
"arial";
if (fontFamilyValue instanceof ListValue) {
ListValue listValue = (ListValue) fontFamilyValue;
//Can be a List? -> take only the first one..
Value firstValue = listValue.item(0);
if (firstValue != null)
fontFamily = firstValue.getStringValue();
}
logger.debug("Font family: " + fontFamily);
IFont font;
if (useVectorFont)
//Vector font
font = FontManager.getInstance().createFont(pa, "arial.ttf", Math.round(fontSize), fillColor, strokeColor);
else
//Bitmap font
font = FontManager.getInstance().createFont(pa, // "Arial", Math.round(fontSize),
fontFamily, Math.round(fontSize), fillColor, strokeColor);
// /*
IFont fontToUse = font;
IFont lastUsedFont = fontToUse;
List<MTTextArea> textAreas = new ArrayList<MTTextArea>();
AttributedCharacterIterator iter = tNode.getAttributedCharacterIterator();
if (//To avoid not loaded fonts or if text ist empty
font != null && iter != null) {
for (int i = iter.getBeginIndex(); i < iter.getEndIndex(); i++) {
char currentChar = iter.setIndex(i);
Set<Attribute> keys = iter.getAllAttributeKeys();
Map<Attribute, Object> charAtts = iter.getAttributes();
Object baseLineShift = charAtts.get(SVGTextElementBridge.BASELINE_SHIFT);
Object paintInfo = charAtts.get(SVGTextElementBridge.PAINT_INFO);
Object charX = charAtts.get(GVTAttributedCharacterIterator.TextAttribute.X);
Object charY = charAtts.get(GVTAttributedCharacterIterator.TextAttribute.Y);
Object charDX = charAtts.get(GVTAttributedCharacterIterator.TextAttribute.DX);
Object charDY = charAtts.get(GVTAttributedCharacterIterator.TextAttribute.DY);
Object charRotation = charAtts.get(GVTAttributedCharacterIterator.TextAttribute.ROTATION);
Object gvtFont = charAtts.get(GVTAttributedCharacterIterator.TextAttribute.GVT_FONT);
Object gvtFonts = charAtts.get(GVTAttributedCharacterIterator.TextAttribute.GVT_FONTS);
Object gvtFontFamilies = charAtts.get(GVTAttributedCharacterIterator.TextAttribute.GVT_FONT_FAMILIES);
Object textCompoundDelimiter = charAtts.get(GVTAttributedCharacterIterator.TextAttribute.TEXT_COMPOUND_DELIMITER);
Object verticalOrientation = charAtts.get(GVTAttributedCharacterIterator.TextAttribute.VERTICAL_ORIENTATION);
logger.debug("Character: " + currentChar + " CharX:" + charX + " CharY: " + charY + " CharDX: " + charDX + " CharDY: " + charDY + " Font: " + gvtFont + " Fonts: " + gvtFonts + " FontFamilies: " + gvtFontFamilies);
AWTGVTFont awtGvtFont = (AWTGVTFont) gvtFont;
if (awtGvtFont != null)
logger.debug("CharfontSize: " + awtGvtFont.getSize());
//FIXME REMOVE, Not working always 0,0
SVGPoint startPosOfChar = SVGTextContentSupport.getStartPositionOfChar(textElement, i);
/////////////////////////////////////
//Get the character information - font, colors
String newFamilyName = new String(fontFamily);
float newFontSize = fontSize;
MTColor newFillColor = new MTColor(fillColor);
MTColor newStrokeColor = new MTColor(strokeColor);
boolean charHasColorInfo = false;
boolean charHasFontInfo = false;
//Get chars paint info
if (paintInfo != null && paintInfo instanceof TextPaintInfo) {
charHasColorInfo = true;
TextPaintInfo texInfo = (TextPaintInfo) paintInfo;
if (texInfo.fillPaint instanceof java.awt.Color) {
java.awt.Color color = (Color) texInfo.fillPaint;
newFillColor.setColor(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha());
}
if (texInfo.strokePaint instanceof java.awt.Color) {
java.awt.Color color = (Color) texInfo.strokePaint;
newStrokeColor.setColor(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha());
}
}
//Get the chars font family and size
GVTFont aGvtFont = null;
if (gvtFonts != null) {
if (gvtFonts instanceof List) {
List<?> fonts = (List<?>) gvtFonts;
for (Iterator<?> iterator = fonts.iterator(); iterator.hasNext(); ) {
Object o = (Object) iterator.next();
if (o instanceof GVTFont) {
aGvtFont = (GVTFont) o;
//logger.debug("Char font family: " + aGvtFont.getFamilyName() + " Size:" + aGvtFont.getSize());
}
}
}
}
if (aGvtFont != null) {
charHasFontInfo = true;
newFamilyName = aGvtFont.getFamilyName();
newFontSize = aGvtFont.getSize();
} else {
logger.error("Character: " + currentChar + " has no font attached.");
}
if (charHasColorInfo && charHasFontInfo) {
logger.debug("Character '" + currentChar + "'-> has font info -> load font!" + " Family: " + newFamilyName + " Fontsize: " + Math.round(newFontSize) + " FillColor: " + newFillColor + " StrokeColor: " + newStrokeColor);
if (useVectorFont)
fontToUse = FontManager.getInstance().createFont(pa, "arial.ttf", Math.round(newFontSize), newFillColor, newStrokeColor);
else
fontToUse = //uses cached font if available
FontManager.getInstance().createFont(//uses cached font if available
pa, // "Arial", Math.round(fontSize),
newFamilyName, Math.round(newFontSize), newFillColor, newStrokeColor);
if (fontToUse == null) {
fontToUse = font;
}
} else {
fontToUse = font;
}
boolean fontChanged = !FontManager.isFontsAreEqual(fontToUse, lastUsedFont);
lastUsedFont = fontToUse;
// //FIXME REMOVE TEST
// fontChanged = true;
///////////////////////////////////////
boolean textPositionChanged = charX != null || charY != null || charDX != null || charDY != null;
//check if equal to last used font and if equal original text font
if (fontChanged || textPositionChanged) //Make a new textarea if the text position changed or if the font changed at the current character
{
MTTextArea previousTextArea = null;
if (!textAreas.isEmpty()) {
previousTextArea = textAreas.get(textAreas.size() - 1);
}
float newXPos = 0;
float newYPos = 0;
//for the DX and DY shift info for the next text area
if (previousTextArea != null) {
PositionAnchor oldAnchor = previousTextArea.getAnchor();
previousTextArea.setAnchor(PositionAnchor.LOWER_RIGHT);
//Calculate last/current textposition for DX and DY use
//add up the last textareas start position end position(width)
Vector3D lastPos = previousTextArea.getPosition(TransformSpace.LOCAL);
newXPos = lastPos.x - previousTextArea.getInnerPadding();
newXPos += (Float) previousTextArea.getUserData("XPos");
newYPos = lastPos.y;
newYPos -= previousTextArea.getInnerPadding();
//FIXME WHY NEVESSARY?
newYPos += //FIXME WHY NEVESSARY?
fontToUse.getFontMaxDescent();
newYPos += (Float) previousTextArea.getUserData("YPos");
previousTextArea.setAnchor(oldAnchor);
}
//IF absolute x or y is present overwrite the position values from the last textarea
if (charX != null)
newXPos = (Float) charX;
if (charY != null)
newYPos = (Float) charY;
if (charDX != null)
newXPos += (Float) charDX;
if (charDY != null)
newYPos += (Float) charDY;
//Create the text area
MTTextArea t = new MTTextArea(pa, fontToUse);
t.setNoFill(true);
t.setNoStroke(true);
textAreas.add(t);
try {
t.setLocalMatrix(new Matrix(currentLocalTransformMatrix));
} catch (Exception e) {
logger.error(e.getMessage());
}
//FIXME TEST
// if (previousTextArea != null && !textPositionChange){
// t.setAnchor(PositionAnchor.LOWER_LEFT);
// t.setUserData("posRelParent", new Vector3D(newXPos , newYPos - fontToUse.getFontMaxDescent() , 0));
// logger.debug("Character '" + currentChar + "' -> Anchor: LOWER_LEFT");
// }else{
Value v = CSSUtilities.getComputedStyle(textElement, SVGCSSEngine.TEXT_ANCHOR_INDEX);
//The textarea is usually fontmaxascent+fontmaxdescent+2*innerPadding big!
switch(v.getStringValue().charAt(0)) {
case 'e':
t.setAnchor(PositionAnchor.LOWER_RIGHT);
t.setUserData("posRelParent", new Vector3D(newXPos - t.getInnerPadding(), newYPos - fontToUse.getFontMaxDescent() + t.getInnerPadding(), 0));
// t.setPositionRelativeToParent(new Vector3D(newXPos, newYPos - font.getFontMaxDescent() , 0));
logger.debug("Character '" + currentChar + "' -> Anchor: LOWER_RIGHT");
break;
case 'm':
t.setAnchor(PositionAnchor.CENTER);
t.setUserData("posRelParent", new Vector3D(newXPos, newYPos - fontToUse.getFontMaxAscent() * 0.5f - fontToUse.getFontMaxDescent() * 0.5f, 0));
// t.setPositionRelativeToParent(new Vector3D(newXPos, newYPos - font.getFontMaxAscent()*0.5f - font.getFontMaxDescent()*0.5f, 0)); //- font.getFontMaxAscent()*0.5f
logger.debug("Character '" + currentChar + "' -> Anchor: CENTER");
break;
default:
t.setAnchor(PositionAnchor.LOWER_LEFT);
t.setUserData("posRelParent", new Vector3D(newXPos - t.getInnerPadding(), newYPos - fontToUse.getFontMaxDescent() + t.getInnerPadding(), 0));
// t.setPositionRelativeToParent(new Vector3D(newXPos, newYPos - font.getFontMaxDescent() , 0));
logger.debug("Character '" + currentChar + "' -> Anchor: LOWER_LEFT");
}
t.setUserData("XPos", newXPos);
t.setUserData("YPos", newYPos);
// }
}
//Add character to the current textarea in the list
if (!textAreas.isEmpty()) {
textAreas.get(textAreas.size() - 1).appendCharByUnicode(new Character(currentChar).toString());
}
}
//Set the positions of the textareas
for (Iterator<MTTextArea> iterator = textAreas.iterator(); iterator.hasNext(); ) {
MTTextArea textArea = (MTTextArea) iterator.next();
logger.debug("Adding text area at: " + (Vector3D) textArea.getUserData("posRelParent"));
textArea.setPositionRelativeToParent((Vector3D) textArea.getUserData("posRelParent"));
}
comps.addAll(textAreas);
}
/*
//This gets only the text of this hierarchy level
StringBuffer result = new StringBuffer();
for (Node n = textElement.getFirstChild();
n != null;
n = n.getNextSibling()) {
switch (n.getNodeType()) {
case Node.ELEMENT_NODE:
break;
case Node.CDATA_SECTION_NODE:
case Node.TEXT_NODE:
result.append(n.getNodeValue());
}
}
logger.debug("TEXTTTT2: " + result);
*/
// */////////////////////
}
}
}
if (node instanceof SVGGraphicsElement) {
//Remove inherited opacity attribute from stack
opacityStack.pop();
}
//traversed in the if (group) block above
if (!(node instanceof SVGOMGElement) && !(node instanceof SVGSVGElement) && !(node instanceof SVGOMSVGElement)) {
traverseChildren(node, comps);
}
}Example 21
| Project: Multitouch-Fluid-Photo-Browser-master File: SVGLoader.java View source code |
/**
* Traverse svg doc.
*
* @param node the node
* @param comps the comps
*/
private void traverseSVGDoc(Node node, ArrayList<MTComponent> comps) {
logger.debug("Traversing: " + node.getNodeName());
//Damit transformationen konsistent sind muss
//jedes tag, da� eine transform attribut hat
//behandelt werden!
//Default
currentLocalTransformMatrix = new Matrix();
//If there is a TRANSFORM attribute parse that and set the
//current transformation matrix to be used with the svg components created after
NamedNodeMap atts = node.getAttributes();
if (atts != null) {
for (int i = 0; i < atts.getLength(); i++) {
Node att = atts.item(i);
if (att.getNodeName().equals(SVG_TRANSFORM_ATTRIBUTE)) {
CustomTransformHandler transFormHandler = new CustomTransformHandler();
TransformListParser transFormListParser = new TransformListParser();
transFormListParser.setTransformListHandler(transFormHandler);
transFormListParser.parse(att.getNodeValue());
//Overwrite current default matrix if the element has its own
//transform defined, will be used at gfx obj creation
currentLocalTransformMatrix = transFormHandler.getResultMatrix();
}
}
}
//For opacity inheritance
if (node instanceof SVGGraphicsElement) {
SVGGraphicsElement svgGfx = (SVGGraphicsElement) node;
//Handle inherited opacity settings
float opac = queryPrimitiveFloatValue(svgGfx, "opacity", 1f);
opacityStack.push(opac *= opacityStack.peek());
}
// if G (GROUP) element, add all children to this element
if (node instanceof SVGOMGElement || node instanceof SVGSVGElement || node instanceof SVGOMSVGElement) {
// SVGOMGElement gElem = (SVGOMGElement)node;
SVGElement gElem = (SVGElement) node;
MTComponent group = new MTComponent(pa);
group.setName(gElem.getTagName());
// Element viewPort = gElem.getViewportElement();
// logger.debug("Viewport " + viewPort.getNodeName());
//Set the <g> group to composite, meaning that it will
//be returned at picking, when one of the children gets picked
group.setComposite(true);
group.setLocalMatrix(currentLocalTransformMatrix);
//(to honor the viewBox and the width/height attributes
if (node instanceof SVGOMSVGElement) {
SVGOMSVGElement svgGom = ((SVGOMSVGElement) node);
Element viewPort = svgGom.getViewportElement();
if (viewPort != null)
logger.debug("Viewport " + viewPort.getNodeName());
// SVGMatrix mat = svgGom.getScreenCTM();
SVGAnimatedLength widthA = svgGom.getWidth();
SVGAnimatedLength heightA = svgGom.getHeight();
SVGLength w = widthA.getBaseVal();
float width = w.getValue();
SVGLength h = heightA.getBaseVal();
float height = h.getValue();
logger.debug("-> SVG Width: " + width + " Height: " + height);
SVGMatrix mat = svgGom.getCTM();
//is assumed by batik -> things may get scaled too small
if (!(width == 1 && height == 1)) {
currentLocalTransformMatrix = new Matrix(mat.getA(), mat.getC(), 0, mat.getE(), mat.getB(), mat.getD(), 0, mat.getF(), 0, 0, 1, 0, 0, 0, 0, 1);
//logger.debug("Matrix: " + currentLocalTransformMatrix);
group.setLocalMatrix(currentLocalTransformMatrix);
}
}
//Make the group pickable and manipulatable
group.setPickable(true);
group.registerInputProcessor(new DragProcessor(pa));
group.setGestureAllowance(DragProcessor.class, true);
group.addGestureListener(DragProcessor.class, (IGestureEventListener) defaultDragAction);
group.registerInputProcessor(new RotateProcessor(pa));
group.addGestureListener(RotateProcessor.class, defaultRotateAction);
group.registerInputProcessor(new ScaleProcessor(pa));
group.addGestureListener(ScaleProcessor.class, defaultScaleAction);
ArrayList<MTComponent> groupChildren = new ArrayList<MTComponent>();
//Traverse the children and add them to a new arraylist
traverseChildren(gElem, groupChildren);
MTComponent[] childComps = groupChildren.toArray(new MTComponent[groupChildren.size()]);
//Add the children to the group
group.addChildren(childComps);
//Add the group to the arraylist of the parent
comps.add(group);
} else //If NOT GROUP
{
if (node instanceof SVGGraphicsElement) {
SVGGraphicsElement svgGfxElem = (SVGGraphicsElement) node;
//IF node isnt a group node just add it to the passed in comps arraylist
try {
//Create a component from the graphicsnode and add it to the parents arraylist
MTComponent liveComponent = handleGraphicsNode(svgGfxElem);
if (liveComponent != null) {
comps.add(liveComponent);
}
} catch (Exception e) {
logger.error("Error handling svg node: " + svgGfxElem.getTagName());
e.printStackTrace();
}
}
//FIXME IMPLEMENT
if (node instanceof SVGOMTSpanElement) {
SVGOMTSpanElement tSpanElement = (SVGOMTSpanElement) node;
}
//FIXME TEST
if (node instanceof SVGOMTextElement) {
boolean useVectorFont = false;
SVGOMTextElement textElement = (SVGOMTextElement) node;
//Get <text> position values (can be a list)
List<Float> xValues = getSVGLengthListAsFloat(textElement.getX().getBaseVal());
List<Float> yValues = getSVGLengthListAsFloat(textElement.getY().getBaseVal());
// /*//Not used
String textContent = TextUtilities.getElementContent(textElement);
textContent = textContent.replaceAll("\\n", "");
textContent = textContent.trim();
/*
//TODO USE?
textElement.getTextLength();
textElement.getRotate();
*/
if (textElement.getSVGContext() instanceof SVGTextElementBridge) {
SVGTextElementBridge b = (SVGTextElementBridge) textElement.getSVGContext();
GraphicsNode gr = b.createGraphicsNode(ctx, textElement);
TextNode tNode = (TextNode) gr;
b.buildGraphicsNode(ctx, textElement, tNode);
List<?> textRuns = tNode.getTextRuns();
logger.debug("Text runs: " + textRuns);
//Get font size
float fontSize = b.getFontSize();
logger.debug("Text:" + " x:" + xValues.get(0) + " y:" + yValues.get(0) + " FontSize: " + fontSize + " Text: '" + textContent + "'");
//Get font FILL
Value fillOpacValue = CSSUtilities.getComputedStyle(textElement, SVGCSSEngine.FILL_OPACITY_INDEX);
float computedfillOpac = PaintServer.convertOpacity(fillOpacValue);
Value fillIndexValue = CSSUtilities.getComputedStyle(textElement, SVGCSSEngine.FILL_INDEX);
Object fill = SVGLoader.getFillOrStroke(textElement, fillIndexValue, computedfillOpac, ctx);
MTColor fillColor = new MTColor(150, 150, 150, 255);
if (fill instanceof java.awt.Color) {
java.awt.Color color = (Color) fill;
fillColor.setColor(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha());
}
//Get STROKE
// Stroke Opacity \\
Value strokeOpacValue = CSSUtilities.getComputedStyle(textElement, SVGCSSEngine.STROKE_OPACITY_INDEX);
float computedStrokeOpacity = PaintServer.convertOpacity(strokeOpacValue);
// Stroke java.awt.Color \\
Value strokeIndexValue = CSSUtilities.getComputedStyle(textElement, SVGCSSEngine.STROKE_INDEX);
Object stroke = SVGLoader.getFillOrStroke(textElement, strokeIndexValue, computedStrokeOpacity, ctx);
MTColor strokeColor = new MTColor(fillColor.getR(), fillColor.getG(), fillColor.getB(), fillColor.getAlpha());
if (stroke instanceof java.awt.Color) {
java.awt.Color color = (Color) stroke;
strokeColor.setColor(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha());
}
//Get the font family
Value fontFamilyValue = CSSUtilities.getComputedStyle(textElement, SVGCSSEngine.FONT_FAMILY_INDEX);
String //DEFAULT
fontFamily = //DEFAULT
"arial";
if (fontFamilyValue instanceof ListValue) {
ListValue listValue = (ListValue) fontFamilyValue;
//Can be a List? -> take only the first one..
Value firstValue = listValue.item(0);
if (firstValue != null)
fontFamily = firstValue.getStringValue();
}
logger.debug("Font family: " + fontFamily);
IFont font;
if (useVectorFont)
//Vector font
font = FontManager.getInstance().createFont(pa, "arial.ttf", Math.round(fontSize), fillColor);
else
//Bitmap font
font = FontManager.getInstance().createFont(pa, // "Arial", Math.round(fontSize),
fontFamily, Math.round(fontSize), fillColor);
// /*
IFont fontToUse = font;
IFont lastUsedFont = fontToUse;
List<MTTextArea> textAreas = new ArrayList<MTTextArea>();
AttributedCharacterIterator iter = tNode.getAttributedCharacterIterator();
if (//To avoid not loaded fonts or if text ist empty
font != null && iter != null) {
for (int i = iter.getBeginIndex(); i < iter.getEndIndex(); i++) {
char currentChar = iter.setIndex(i);
Set<Attribute> keys = iter.getAllAttributeKeys();
Map<Attribute, Object> charAtts = iter.getAttributes();
Object baseLineShift = charAtts.get(SVGTextElementBridge.BASELINE_SHIFT);
Object paintInfo = charAtts.get(SVGTextElementBridge.PAINT_INFO);
Object charX = charAtts.get(GVTAttributedCharacterIterator.TextAttribute.X);
Object charY = charAtts.get(GVTAttributedCharacterIterator.TextAttribute.Y);
Object charDX = charAtts.get(GVTAttributedCharacterIterator.TextAttribute.DX);
Object charDY = charAtts.get(GVTAttributedCharacterIterator.TextAttribute.DY);
Object charRotation = charAtts.get(GVTAttributedCharacterIterator.TextAttribute.ROTATION);
Object gvtFont = charAtts.get(GVTAttributedCharacterIterator.TextAttribute.GVT_FONT);
Object gvtFonts = charAtts.get(GVTAttributedCharacterIterator.TextAttribute.GVT_FONTS);
Object gvtFontFamilies = charAtts.get(GVTAttributedCharacterIterator.TextAttribute.GVT_FONT_FAMILIES);
Object textCompoundDelimiter = charAtts.get(GVTAttributedCharacterIterator.TextAttribute.TEXT_COMPOUND_DELIMITER);
Object verticalOrientation = charAtts.get(GVTAttributedCharacterIterator.TextAttribute.VERTICAL_ORIENTATION);
logger.debug("Character: " + currentChar + " CharX:" + charX + " CharY: " + charY + " CharDX: " + charDX + " CharDY: " + charDY + " Font: " + gvtFont + " Fonts: " + gvtFonts + " FontFamilies: " + gvtFontFamilies);
AWTGVTFont awtGvtFont = (AWTGVTFont) gvtFont;
if (awtGvtFont != null)
logger.debug("CharfontSize: " + awtGvtFont.getSize());
//FIXME REMOVE, Not working always 0,0
SVGPoint startPosOfChar = SVGTextContentSupport.getStartPositionOfChar(textElement, i);
/////////////////////////////////////
//Get the character information - font, colors
String newFamilyName = fontFamily;
float newFontSize = fontSize;
MTColor newFillColor = new MTColor(fillColor);
MTColor newStrokeColor = new MTColor(strokeColor);
boolean charHasColorInfo = false;
boolean charHasFontInfo = false;
//Get chars paint info
if (paintInfo != null && paintInfo instanceof TextPaintInfo) {
charHasColorInfo = true;
TextPaintInfo texInfo = (TextPaintInfo) paintInfo;
if (texInfo.fillPaint instanceof java.awt.Color) {
java.awt.Color color = (Color) texInfo.fillPaint;
newFillColor.setColor(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha());
}
if (texInfo.strokePaint instanceof java.awt.Color) {
java.awt.Color color = (Color) texInfo.strokePaint;
newStrokeColor.setColor(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha());
}
}
//Get the chars font family and size
GVTFont aGvtFont = null;
if (gvtFonts != null) {
if (gvtFonts instanceof List) {
List<?> fonts = (List<?>) gvtFonts;
for (Object o : fonts) {
if (o instanceof GVTFont) {
aGvtFont = (GVTFont) o;
//logger.debug("Char font family: " + aGvtFont.getFamilyName() + " Size:" + aGvtFont.getSize());
}
}
}
}
if (aGvtFont != null) {
charHasFontInfo = true;
newFamilyName = aGvtFont.getFamilyName();
newFontSize = aGvtFont.getSize();
} else {
logger.error("Character: " + currentChar + " has no font attached.");
}
if (charHasColorInfo && charHasFontInfo) {
logger.debug("Character '" + currentChar + "'-> has font info -> load font!" + " Family: " + newFamilyName + " Fontsize: " + Math.round(newFontSize) + " FillColor: " + newFillColor + " StrokeColor: " + newStrokeColor);
if (useVectorFont)
fontToUse = FontManager.getInstance().createFont(pa, "arial.ttf", Math.round(newFontSize), newFillColor);
else
fontToUse = //uses cached font if available
FontManager.getInstance().createFont(//uses cached font if available
pa, // "Arial", Math.round(fontSize),
newFamilyName, Math.round(newFontSize), newFillColor);
if (fontToUse == null) {
fontToUse = font;
}
} else {
fontToUse = font;
}
boolean fontChanged = !FontManager.isFontsAreEqual(fontToUse, lastUsedFont);
lastUsedFont = fontToUse;
// //FIXME REMOVE TEST
// fontChanged = true;
///////////////////////////////////////
boolean textPositionChanged = charX != null || charY != null || charDX != null || charDY != null;
//check if equal to last used font and if equal original text font
if (fontChanged || textPositionChanged) //Make a new textarea if the text position changed or if the font changed at the current character
{
MTTextArea previousTextArea = null;
if (!textAreas.isEmpty()) {
previousTextArea = textAreas.get(textAreas.size() - 1);
}
float newXPos = 0;
float newYPos = 0;
//for the DX and DY shift info for the next text area
if (previousTextArea != null) {
PositionAnchor oldAnchor = previousTextArea.getAnchor();
// previousTextArea.setAnchor(PositionAnchor.LOWER_RIGHT);
previousTextArea.setAnchor(PositionAnchor.UPPER_LEFT);
//Calculate last/current textposition for DX and DY use
//add up the last textareas start position end position(width)
Vector3D lastPos = previousTextArea.getPosition(TransformSpace.LOCAL);
// lastPos.addLocal(new Vector3D(previousTextArea.getWidthXY(TransformSpace.LOCAL) - 1 * previousTextArea.getInnerPaddingLeft(),0));
lastPos.addLocal(new Vector3D(previousTextArea.getWidthXY(TransformSpace.LOCAL) - 2 * previousTextArea.getInnerPaddingLeft(), 0));
// newXPos = lastPos.x - previousTextArea.getInnerPaddingLeft();
newXPos = lastPos.x;
newXPos += (Float) previousTextArea.getUserData("XPos");
newYPos = lastPos.y;
// newYPos -= previousTextArea.getInnerPaddingTop();
// newYPos += fontToUse.getFontMaxDescent(); //FIXME WHY NEVESSARY?
newYPos += (Float) previousTextArea.getUserData("YPos");
previousTextArea.setAnchor(oldAnchor);
}
//IF absolute x or y is present overwrite the position values from the last textarea
if (charX != null)
newXPos = (Float) charX;
if (charY != null)
newYPos = (Float) charY;
if (charDX != null)
newXPos += (Float) charDX;
if (charDY != null)
newYPos += (Float) charDY;
// Create the text area \\
MTTextArea t = new MTTextArea(pa, fontToUse);
t.setNoFill(true);
t.setNoStroke(true);
textAreas.add(t);
try {
t.setLocalMatrix(new Matrix(currentLocalTransformMatrix));
} catch (Exception e) {
logger.error(e.getMessage());
}
//FIXME TEST
// if (previousTextArea != null && !textPositionChange){
// t.setAnchor(PositionAnchor.LOWER_LEFT);
// t.setUserData("posRelParent", new Vector3D(newXPos , newYPos - fontToUse.getFontMaxDescent() , 0));
// logger.debug("Character '" + currentChar + "' -> Anchor: LOWER_LEFT");
// }else{
Value v = CSSUtilities.getComputedStyle(textElement, SVGCSSEngine.TEXT_ANCHOR_INDEX);
//The textarea is usually fontmaxascent+fontmaxdescent+2*innerPadding big!
switch(v.getStringValue().charAt(0)) {
case 'e':
t.setAnchor(PositionAnchor.LOWER_RIGHT);
t.setUserData("posRelParent", new Vector3D((newXPos + t.getInnerPaddingLeft()), newYPos - fontToUse.getFontMaxDescent() + t.getInnerPaddingTop(), 0));
// t.setPositionRelativeToParent(new Vector3D(newXPos, newYPos - font.getFontMaxDescent() , 0));
logger.debug("Character '" + currentChar + "' -> Anchor: LOWER_RIGHT");
break;
//text-anchor="middle"
case 'm':
t.setAnchor(PositionAnchor.CENTER);
// t.setUserData("posRelParent", new Vector3D(newXPos, newYPos - fontToUse.getFontMaxAscent()*0.5f - fontToUse.getFontMaxDescent()*0.5f , 0));
// t.setUserData("posRelParent", new Vector3D(newXPos, newYPos - fontToUse.getFontAbsoluteHeight()*0.5f + t.getInnerPaddingTop() , 0));
// t.setPositionRelativeToParent(new Vector3D(newXPos, newYPos - font.getFontMaxAscent()*0.5f - font.getFontMaxDescent()*0.5f, 0)); //- font.getFontMaxAscent()*0.5f
logger.debug("Character '" + currentChar + "' -> Anchor: CENTER");
t.setUserData("posRelParent", new Vector3D((newXPos), (newYPos - fontToUse.getFontMaxDescent() + t.getInnerPaddingTop()) - t.getHeightXY(TransformSpace.LOCAL) / 2f, 0));
break;
//text-anchor="start" //default!
default:
t.setAnchor(PositionAnchor.LOWER_LEFT);
// t.setUserData("posRelParent", new Vector3D(newXPos -t.getInnerPaddingLeft(), newYPos - fontToUse.getFontMaxDescent() + t.getInnerPaddingTop() , 0));
t.setUserData("posRelParent", new Vector3D(newXPos - t.getInnerPaddingLeft(), newYPos - fontToUse.getFontMaxDescent() + t.getInnerPaddingTop(), 0));
// t.setAnchor(PositionAnchor.UPPER_LEFT);
// t.setUserData("posRelParent", new Vector3D(newXPos -t.getInnerPaddingLeft(), newYPos, 0));
// t.setPositionRelativeToParent(new Vector3D(newXPos, newYPos - font.getFontMaxDescent() , 0));
logger.debug("Character '" + currentChar + "' -> Anchor: LOWER_LEFT");
}
t.setUserData("XPos", newXPos);
t.setUserData("YPos", newYPos);
// }
}
//Add character to the current textarea in the list
if (!textAreas.isEmpty()) {
textAreas.get(textAreas.size() - 1).appendCharByUnicode(Character.toString(currentChar));
}
}
//Set the positions of the textareas
for (MTTextArea textArea : textAreas) {
logger.debug("Adding text area at: " + (Vector3D) textArea.getUserData("posRelParent"));
textArea.setPositionRelativeToParent((Vector3D) textArea.getUserData("posRelParent"));
}
comps.addAll(textAreas);
}
/*
//This gets only the text of this hierarchy level
StringBuffer result = new StringBuffer();
for (Node n = textElement.getFirstChild();
n != null;
n = n.getNextSibling()) {
switch (n.getNodeType()) {
case Node.ELEMENT_NODE:
break;
case Node.CDATA_SECTION_NODE:
case Node.TEXT_NODE:
result.append(n.getNodeValue());
}
}
logger.debug("TEXTTTT2: " + result);
*/
// */////////////////////
}
}
}
if (node instanceof SVGGraphicsElement) {
//Remove inherited opacity attribute from stack
opacityStack.pop();
}
//traversed in the if (group) block above
if (!(node instanceof SVGOMGElement) && !(node instanceof SVGSVGElement) && !(node instanceof SVGOMSVGElement)) {
traverseChildren(node, comps);
}
}Example 22
| Project: VAFusion2-master File: SVGLoader.java View source code |
/**
* Traverse svg doc.
*
* @param node the node
* @param comps the comps
*/
private void traverseSVGDoc(Node node, ArrayList<MTComponent> comps) {
logger.debug("Traversing: " + node.getNodeName());
//Damit transformationen konsistent sind muss
//jedes tag, da� eine transform attribut hat
//behandelt werden!
//Default
currentLocalTransformMatrix = new Matrix();
//If there is a TRANSFORM attribute parse that and set the
//current transformation matrix to be used with the svg components created after
NamedNodeMap atts = node.getAttributes();
if (atts != null) {
for (int i = 0; i < atts.getLength(); i++) {
Node att = atts.item(i);
if (att.getNodeName().equals(SVG_TRANSFORM_ATTRIBUTE)) {
CustomTransformHandler transFormHandler = new CustomTransformHandler();
TransformListParser transFormListParser = new TransformListParser();
transFormListParser.setTransformListHandler(transFormHandler);
transFormListParser.parse(att.getNodeValue());
//Overwrite current default matrix if the element has its own
//transform defined, will be used at gfx obj creation
currentLocalTransformMatrix = transFormHandler.getResultMatrix();
}
}
}
//For opacity inheritance
if (node instanceof SVGGraphicsElement) {
SVGGraphicsElement svgGfx = (SVGGraphicsElement) node;
//Handle inherited opacity settings
float opac = queryPrimitiveFloatValue(svgGfx, "opacity", 1f);
opacityStack.push(opac *= opacityStack.peek().floatValue());
}
// if G (GROUP) element, add all children to this element
if (node instanceof SVGOMGElement || node instanceof SVGSVGElement || node instanceof SVGOMSVGElement) {
// SVGOMGElement gElem = (SVGOMGElement)node;
SVGElement gElem = (SVGElement) node;
MTComponent group = new MTComponent(pa);
group.setName(gElem.getTagName());
// Element viewPort = gElem.getViewportElement();
// logger.debug("Viewport " + viewPort.getNodeName());
//Set the <g> group to composite, meaning that it will
//be returned at picking, when one of the children gets picked
group.setComposite(true);
group.setLocalMatrix(currentLocalTransformMatrix);
//(to honor the viewBox and the width/height attributes
if (node instanceof SVGOMSVGElement) {
SVGOMSVGElement svgGom = ((SVGOMSVGElement) node);
Element viewPort = svgGom.getViewportElement();
if (viewPort != null)
logger.debug("Viewport " + viewPort.getNodeName());
// SVGMatrix mat = svgGom.getScreenCTM();
SVGAnimatedLength widthA = svgGom.getWidth();
SVGAnimatedLength heightA = svgGom.getHeight();
SVGLength w = widthA.getBaseVal();
float width = w.getValue();
SVGLength h = heightA.getBaseVal();
float height = h.getValue();
logger.debug("-> SVG Width: " + width + " Height: " + height);
SVGMatrix mat = svgGom.getCTM();
//is assumed by batik -> things may get scaled too small
if (!(width == 1 && height == 1)) {
currentLocalTransformMatrix = new Matrix(mat.getA(), mat.getC(), 0, mat.getE(), mat.getB(), mat.getD(), 0, mat.getF(), 0, 0, 1, 0, 0, 0, 0, 1);
//logger.debug("Matrix: " + currentLocalTransformMatrix);
group.setLocalMatrix(currentLocalTransformMatrix);
}
}
//Make the group pickable and manipulatable
group.setPickable(true);
group.registerInputProcessor(new DragProcessor(pa));
group.setGestureAllowance(DragProcessor.class, true);
group.addGestureListener(DragProcessor.class, (IGestureEventListener) defaultDragAction);
group.registerInputProcessor(new RotateProcessor(pa));
group.addGestureListener(RotateProcessor.class, defaultRotateAction);
group.registerInputProcessor(new ScaleProcessor(pa));
group.addGestureListener(ScaleProcessor.class, defaultScaleAction);
ArrayList<MTComponent> groupChildren = new ArrayList<MTComponent>();
//Traverse the children and add them to a new arraylist
traverseChildren(gElem, groupChildren);
MTComponent[] childComps = (MTComponent[]) groupChildren.toArray(new MTComponent[groupChildren.size()]);
//Add the children to the group
group.addChildren(childComps);
//Add the group to the arraylist of the parent
comps.add(group);
} else //If NOT GROUP
{
if (node instanceof SVGGraphicsElement) {
SVGGraphicsElement svgGfxElem = (SVGGraphicsElement) node;
//IF node isnt a group node just add it to the passed in comps arraylist
try {
//Create a component from the graphicsnode and add it to the parents arraylist
MTComponent liveComponent = handleGraphicsNode(svgGfxElem);
if (liveComponent != null) {
comps.add(liveComponent);
}
} catch (Exception e) {
logger.error("Error handling svg node: " + svgGfxElem.getTagName());
e.printStackTrace();
}
}
//FIXME IMPLEMENT
if (node instanceof SVGOMTSpanElement) {
SVGOMTSpanElement tSpanElement = (SVGOMTSpanElement) node;
}
//FIXME TEST
if (node instanceof SVGOMTextElement) {
boolean useVectorFont = false;
SVGOMTextElement textElement = (SVGOMTextElement) node;
//Get <text> position values (can be a list)
List<Float> xValues = getSVGLengthListAsFloat(textElement.getX().getBaseVal());
List<Float> yValues = getSVGLengthListAsFloat(textElement.getY().getBaseVal());
// /*//Not used
String textContent = TextUtilities.getElementContent(textElement);
textContent = textContent.replaceAll("\\n", "");
textContent = textContent.trim();
/*
//TODO USE?
textElement.getTextLength();
textElement.getRotate();
*/
if (textElement.getSVGContext() instanceof SVGTextElementBridge) {
SVGTextElementBridge b = (SVGTextElementBridge) textElement.getSVGContext();
GraphicsNode gr = b.createGraphicsNode(ctx, textElement);
TextNode tNode = (TextNode) gr;
b.buildGraphicsNode(ctx, textElement, tNode);
List<?> textRuns = tNode.getTextRuns();
logger.debug("Text runs: " + textRuns);
//Get font size
float fontSize = b.getFontSize();
logger.debug("Text:" + " x:" + xValues.get(0) + " y:" + yValues.get(0) + " FontSize: " + fontSize + " Text: '" + textContent + "'");
//Get font FILL
Value fillOpacValue = CSSUtilities.getComputedStyle(textElement, SVGCSSEngine.FILL_OPACITY_INDEX);
float computedfillOpac = PaintServer.convertOpacity(fillOpacValue);
Value fillIndexValue = CSSUtilities.getComputedStyle(textElement, SVGCSSEngine.FILL_INDEX);
Object fill = SVGLoader.getFillOrStroke(textElement, fillIndexValue, computedfillOpac, ctx);
MTColor fillColor = new MTColor(150, 150, 150, 255);
if (fill instanceof java.awt.Color) {
java.awt.Color color = (Color) fill;
fillColor.setColor(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha());
}
//Get STROKE
// Stroke Opacity \\
Value strokeOpacValue = CSSUtilities.getComputedStyle(textElement, SVGCSSEngine.STROKE_OPACITY_INDEX);
float computedStrokeOpacity = PaintServer.convertOpacity(strokeOpacValue);
// Stroke java.awt.Color \\
Value strokeIndexValue = CSSUtilities.getComputedStyle(textElement, SVGCSSEngine.STROKE_INDEX);
Object stroke = SVGLoader.getFillOrStroke(textElement, strokeIndexValue, computedStrokeOpacity, ctx);
MTColor strokeColor = new MTColor(fillColor.getR(), fillColor.getG(), fillColor.getB(), fillColor.getAlpha());
if (stroke instanceof java.awt.Color) {
java.awt.Color color = (Color) stroke;
strokeColor.setColor(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha());
}
//Get the font family
Value fontFamilyValue = CSSUtilities.getComputedStyle(textElement, SVGCSSEngine.FONT_FAMILY_INDEX);
String //DEFAULT
fontFamily = //DEFAULT
"arial";
if (fontFamilyValue instanceof ListValue) {
ListValue listValue = (ListValue) fontFamilyValue;
//Can be a List? -> take only the first one..
Value firstValue = listValue.item(0);
if (firstValue != null)
fontFamily = firstValue.getStringValue();
}
logger.debug("Font family: " + fontFamily);
IFont font;
if (useVectorFont)
//Vector font
font = FontManager.getInstance().createFont(pa, "arial.ttf", Math.round(fontSize), fillColor, strokeColor);
else
//Bitmap font
font = FontManager.getInstance().createFont(pa, // "Arial", Math.round(fontSize),
fontFamily, Math.round(fontSize), fillColor, strokeColor);
// /*
IFont fontToUse = font;
IFont lastUsedFont = fontToUse;
List<MTTextArea> textAreas = new ArrayList<MTTextArea>();
AttributedCharacterIterator iter = tNode.getAttributedCharacterIterator();
if (//To avoid not loaded fonts or if text ist empty
font != null && iter != null) {
for (int i = iter.getBeginIndex(); i < iter.getEndIndex(); i++) {
char currentChar = iter.setIndex(i);
Set<Attribute> keys = iter.getAllAttributeKeys();
Map<Attribute, Object> charAtts = iter.getAttributes();
Object baseLineShift = charAtts.get(SVGTextElementBridge.BASELINE_SHIFT);
Object paintInfo = charAtts.get(SVGTextElementBridge.PAINT_INFO);
Object charX = charAtts.get(GVTAttributedCharacterIterator.TextAttribute.X);
Object charY = charAtts.get(GVTAttributedCharacterIterator.TextAttribute.Y);
Object charDX = charAtts.get(GVTAttributedCharacterIterator.TextAttribute.DX);
Object charDY = charAtts.get(GVTAttributedCharacterIterator.TextAttribute.DY);
Object charRotation = charAtts.get(GVTAttributedCharacterIterator.TextAttribute.ROTATION);
Object gvtFont = charAtts.get(GVTAttributedCharacterIterator.TextAttribute.GVT_FONT);
Object gvtFonts = charAtts.get(GVTAttributedCharacterIterator.TextAttribute.GVT_FONTS);
Object gvtFontFamilies = charAtts.get(GVTAttributedCharacterIterator.TextAttribute.GVT_FONT_FAMILIES);
Object textCompoundDelimiter = charAtts.get(GVTAttributedCharacterIterator.TextAttribute.TEXT_COMPOUND_DELIMITER);
Object verticalOrientation = charAtts.get(GVTAttributedCharacterIterator.TextAttribute.VERTICAL_ORIENTATION);
logger.debug("Character: " + currentChar + " CharX:" + charX + " CharY: " + charY + " CharDX: " + charDX + " CharDY: " + charDY + " Font: " + gvtFont + " Fonts: " + gvtFonts + " FontFamilies: " + gvtFontFamilies);
AWTGVTFont awtGvtFont = (AWTGVTFont) gvtFont;
if (awtGvtFont != null)
logger.debug("CharfontSize: " + awtGvtFont.getSize());
//FIXME REMOVE, Not working always 0,0
SVGPoint startPosOfChar = SVGTextContentSupport.getStartPositionOfChar(textElement, i);
/////////////////////////////////////
//Get the character information - font, colors
String newFamilyName = new String(fontFamily);
float newFontSize = fontSize;
MTColor newFillColor = new MTColor(fillColor);
MTColor newStrokeColor = new MTColor(strokeColor);
boolean charHasColorInfo = false;
boolean charHasFontInfo = false;
//Get chars paint info
if (paintInfo != null && paintInfo instanceof TextPaintInfo) {
charHasColorInfo = true;
TextPaintInfo texInfo = (TextPaintInfo) paintInfo;
if (texInfo.fillPaint instanceof java.awt.Color) {
java.awt.Color color = (Color) texInfo.fillPaint;
newFillColor.setColor(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha());
}
if (texInfo.strokePaint instanceof java.awt.Color) {
java.awt.Color color = (Color) texInfo.strokePaint;
newStrokeColor.setColor(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha());
}
}
//Get the chars font family and size
GVTFont aGvtFont = null;
if (gvtFonts != null) {
if (gvtFonts instanceof List) {
List<?> fonts = (List<?>) gvtFonts;
for (Iterator<?> iterator = fonts.iterator(); iterator.hasNext(); ) {
Object o = (Object) iterator.next();
if (o instanceof GVTFont) {
aGvtFont = (GVTFont) o;
//logger.debug("Char font family: " + aGvtFont.getFamilyName() + " Size:" + aGvtFont.getSize());
}
}
}
}
if (aGvtFont != null) {
charHasFontInfo = true;
newFamilyName = aGvtFont.getFamilyName();
newFontSize = aGvtFont.getSize();
} else {
logger.error("Character: " + currentChar + " has no font attached.");
}
if (charHasColorInfo && charHasFontInfo) {
logger.debug("Character '" + currentChar + "'-> has font info -> load font!" + " Family: " + newFamilyName + " Fontsize: " + Math.round(newFontSize) + " FillColor: " + newFillColor + " StrokeColor: " + newStrokeColor);
if (useVectorFont)
fontToUse = FontManager.getInstance().createFont(pa, "arial.ttf", Math.round(newFontSize), newFillColor, newStrokeColor);
else
fontToUse = //uses cached font if available
FontManager.getInstance().createFont(//uses cached font if available
pa, // "Arial", Math.round(fontSize),
newFamilyName, Math.round(newFontSize), newFillColor, newStrokeColor);
if (fontToUse == null) {
fontToUse = font;
}
} else {
fontToUse = font;
}
boolean fontChanged = !FontManager.isFontsAreEqual(fontToUse, lastUsedFont);
lastUsedFont = fontToUse;
// //FIXME REMOVE TEST
// fontChanged = true;
///////////////////////////////////////
boolean textPositionChanged = charX != null || charY != null || charDX != null || charDY != null;
//check if equal to last used font and if equal original text font
if (fontChanged || textPositionChanged) //Make a new textarea if the text position changed or if the font changed at the current character
{
MTTextArea previousTextArea = null;
if (!textAreas.isEmpty()) {
previousTextArea = textAreas.get(textAreas.size() - 1);
}
float newXPos = 0;
float newYPos = 0;
//for the DX and DY shift info for the next text area
if (previousTextArea != null) {
PositionAnchor oldAnchor = previousTextArea.getAnchor();
// previousTextArea.setAnchor(PositionAnchor.LOWER_RIGHT);
previousTextArea.setAnchor(PositionAnchor.UPPER_LEFT);
//Calculate last/current textposition for DX and DY use
//add up the last textareas start position end position(width)
Vector3D lastPos = previousTextArea.getPosition(TransformSpace.LOCAL);
// lastPos.addLocal(new Vector3D(previousTextArea.getWidthXY(TransformSpace.LOCAL) - 1 * previousTextArea.getInnerPaddingLeft(),0));
lastPos.addLocal(new Vector3D(previousTextArea.getWidthXY(TransformSpace.LOCAL) - 2 * previousTextArea.getInnerPaddingLeft(), 0));
// newXPos = lastPos.x - previousTextArea.getInnerPaddingLeft();
newXPos = lastPos.x;
newXPos += (Float) previousTextArea.getUserData("XPos");
newYPos = lastPos.y;
// newYPos -= previousTextArea.getInnerPaddingTop();
// newYPos += fontToUse.getFontMaxDescent(); //FIXME WHY NEVESSARY?
newYPos += (Float) previousTextArea.getUserData("YPos");
previousTextArea.setAnchor(oldAnchor);
}
//IF absolute x or y is present overwrite the position values from the last textarea
if (charX != null)
newXPos = (Float) charX;
if (charY != null)
newYPos = (Float) charY;
if (charDX != null)
newXPos += (Float) charDX;
if (charDY != null)
newYPos += (Float) charDY;
// Create the text area \\
MTTextArea t = new MTTextArea(pa, fontToUse);
t.setNoFill(true);
t.setNoStroke(true);
textAreas.add(t);
try {
t.setLocalMatrix(new Matrix(currentLocalTransformMatrix));
} catch (Exception e) {
logger.error(e.getMessage());
}
//FIXME TEST
// if (previousTextArea != null && !textPositionChange){
// t.setAnchor(PositionAnchor.LOWER_LEFT);
// t.setUserData("posRelParent", new Vector3D(newXPos , newYPos - fontToUse.getFontMaxDescent() , 0));
// logger.debug("Character '" + currentChar + "' -> Anchor: LOWER_LEFT");
// }else{
Value v = CSSUtilities.getComputedStyle(textElement, SVGCSSEngine.TEXT_ANCHOR_INDEX);
//The textarea is usually fontmaxascent+fontmaxdescent+2*innerPadding big!
switch(v.getStringValue().charAt(0)) {
case 'e':
t.setAnchor(PositionAnchor.LOWER_RIGHT);
t.setUserData("posRelParent", new Vector3D((newXPos + t.getInnerPaddingLeft()), newYPos - fontToUse.getFontMaxDescent() + t.getInnerPaddingTop(), 0));
// t.setPositionRelativeToParent(new Vector3D(newXPos, newYPos - font.getFontMaxDescent() , 0));
logger.debug("Character '" + currentChar + "' -> Anchor: LOWER_RIGHT");
break;
//text-anchor="middle"
case 'm':
t.setAnchor(PositionAnchor.CENTER);
// t.setUserData("posRelParent", new Vector3D(newXPos, newYPos - fontToUse.getFontMaxAscent()*0.5f - fontToUse.getFontMaxDescent()*0.5f , 0));
// t.setUserData("posRelParent", new Vector3D(newXPos, newYPos - fontToUse.getFontAbsoluteHeight()*0.5f + t.getInnerPaddingTop() , 0));
// t.setPositionRelativeToParent(new Vector3D(newXPos, newYPos - font.getFontMaxAscent()*0.5f - font.getFontMaxDescent()*0.5f, 0)); //- font.getFontMaxAscent()*0.5f
logger.debug("Character '" + currentChar + "' -> Anchor: CENTER");
t.setUserData("posRelParent", new Vector3D((newXPos), (newYPos - fontToUse.getFontMaxDescent() + t.getInnerPaddingTop()) - t.getHeightXY(TransformSpace.LOCAL) / 2f, 0));
break;
//text-anchor="start" //default!
default:
t.setAnchor(PositionAnchor.LOWER_LEFT);
// t.setUserData("posRelParent", new Vector3D(newXPos -t.getInnerPaddingLeft(), newYPos - fontToUse.getFontMaxDescent() + t.getInnerPaddingTop() , 0));
t.setUserData("posRelParent", new Vector3D(newXPos - t.getInnerPaddingLeft(), newYPos - fontToUse.getFontMaxDescent() + t.getInnerPaddingTop(), 0));
// t.setAnchor(PositionAnchor.UPPER_LEFT);
// t.setUserData("posRelParent", new Vector3D(newXPos -t.getInnerPaddingLeft(), newYPos, 0));
// t.setPositionRelativeToParent(new Vector3D(newXPos, newYPos - font.getFontMaxDescent() , 0));
logger.debug("Character '" + currentChar + "' -> Anchor: LOWER_LEFT");
}
t.setUserData("XPos", newXPos);
t.setUserData("YPos", newYPos);
// }
}
//Add character to the current textarea in the list
if (!textAreas.isEmpty()) {
textAreas.get(textAreas.size() - 1).appendCharByUnicode(new Character(currentChar).toString());
}
}
//Set the positions of the textareas
for (Iterator<MTTextArea> iterator = textAreas.iterator(); iterator.hasNext(); ) {
MTTextArea textArea = (MTTextArea) iterator.next();
logger.debug("Adding text area at: " + (Vector3D) textArea.getUserData("posRelParent"));
textArea.setPositionRelativeToParent((Vector3D) textArea.getUserData("posRelParent"));
}
comps.addAll(textAreas);
}
/*
//This gets only the text of this hierarchy level
StringBuffer result = new StringBuffer();
for (Node n = textElement.getFirstChild();
n != null;
n = n.getNextSibling()) {
switch (n.getNodeType()) {
case Node.ELEMENT_NODE:
break;
case Node.CDATA_SECTION_NODE:
case Node.TEXT_NODE:
result.append(n.getNodeValue());
}
}
logger.debug("TEXTTTT2: " + result);
*/
// */////////////////////
}
}
}
if (node instanceof SVGGraphicsElement) {
//Remove inherited opacity attribute from stack
opacityStack.pop();
}
//traversed in the if (group) block above
if (!(node instanceof SVGOMGElement) && !(node instanceof SVGSVGElement) && !(node instanceof SVGOMSVGElement)) {
traverseChildren(node, comps);
}
}