431
// in java/net/n3/nanoxml/XMLUtil.java
static void skipComment(IXMLReader reader)
throws IOException,
XMLParseException
{
if (reader.read() != '-') {
XMLUtil.errorExpectedInput(reader.getSystemID(),
reader.getLineNr(),
"<!--");
}
int dashesRead = 0;
for (;;) {
char ch = reader.read();
switch (ch) {
case '-':
dashesRead++;
break;
case '>':
if (dashesRead == 2) {
return;
}
default:
dashesRead = 0;
}
}
}
// in java/net/n3/nanoxml/XMLUtil.java
static void skipTag(IXMLReader reader)
throws IOException,
XMLParseException
{
int level = 1;
while (level > 0) {
char ch = reader.read();
switch (ch) {
case '<':
++level;
break;
case '>':
--level;
break;
}
}
}
// in java/net/n3/nanoxml/XMLUtil.java
static String scanPublicID(StringBuffer publicID,
IXMLReader reader)
throws IOException,
XMLParseException
{
if (! XMLUtil.checkLiteral(reader, "UBLIC")) {
return null;
}
XMLUtil.skipWhitespace(reader, null);
publicID.append(XMLUtil.scanString(reader, '\0', null));
XMLUtil.skipWhitespace(reader, null);
return XMLUtil.scanString(reader, '\0', null);
}
// in java/net/n3/nanoxml/XMLUtil.java
static String scanSystemID(IXMLReader reader)
throws IOException,
XMLParseException
{
if (! XMLUtil.checkLiteral(reader, "YSTEM")) {
return null;
}
XMLUtil.skipWhitespace(reader, null);
return XMLUtil.scanString(reader, '\0', null);
}
// in java/net/n3/nanoxml/XMLUtil.java
static String scanIdentifier(IXMLReader reader)
throws IOException,
XMLParseException
{
StringBuffer result = new StringBuffer();
for (;;) {
char ch = reader.read();
if ((ch == '_') || (ch == ':') || (ch == '-') || (ch == '.')
|| ((ch >= 'a') && (ch <= 'z'))
|| ((ch >= 'A') && (ch <= 'Z'))
|| ((ch >= '0') && (ch <= '9')) || (ch > '\u007E')) {
result.append(ch);
} else {
reader.unread(ch);
break;
}
}
return result.toString();
}
// in java/net/n3/nanoxml/XMLUtil.java
static String scanString(IXMLReader reader,
char entityChar,
IXMLEntityResolver entityResolver)
throws IOException,
XMLParseException
{
StringBuffer result = new StringBuffer();
int startingLevel = reader.getStreamLevel();
char delim = reader.read();
if ((delim != '\'') && (delim != '"')) {
XMLUtil.errorExpectedInput(reader.getSystemID(),
reader.getLineNr(),
"delimited string");
}
for (;;) {
String str = XMLUtil.read(reader, entityChar);
char ch = str.charAt(0);
if (ch == entityChar) {
if (str.charAt(1) == '#') {
result.append(XMLUtil.processCharLiteral(str));
} else {
XMLUtil.processEntity(str, reader, entityResolver);
}
} else if (ch == '&') {
reader.unread(ch);
str = XMLUtil.read(reader, '&');
if (str.charAt(1) == '#') {
result.append(XMLUtil.processCharLiteral(str));
} else {
result.append(str);
}
} else if (reader.getStreamLevel() == startingLevel) {
if (ch == delim) {
break;
} else if ((ch == 9) || (ch == 10) || (ch == 13)) {
result.append(' ');
} else {
result.append(ch);
}
} else {
result.append(ch);
}
}
return result.toString();
}
// in java/net/n3/nanoxml/XMLUtil.java
static void processEntity(String entity,
IXMLReader reader,
IXMLEntityResolver entityResolver)
throws IOException,
XMLParseException
{
entity = entity.substring(1, entity.length() - 1);
Reader entityReader = entityResolver.getEntity(reader, entity);
if (entityReader == null) {
XMLUtil.errorInvalidEntity(reader.getSystemID(),
reader.getLineNr(),
entity);
}
boolean externalEntity = entityResolver.isExternalEntity(entity);
reader.startNewStream(entityReader, !externalEntity);
}
// in java/net/n3/nanoxml/XMLUtil.java
static char processCharLiteral(String entity)
throws IOException,
XMLParseException
{
if (entity.charAt(2) == 'x') {
entity = entity.substring(3, entity.length() - 1);
return (char) Integer.parseInt(entity, 16);
} else {
entity = entity.substring(2, entity.length() - 1);
return (char) Integer.parseInt(entity, 10);
}
}
// in java/net/n3/nanoxml/XMLUtil.java
static void skipWhitespace(IXMLReader reader,
StringBuffer buffer)
throws IOException
{
char ch;
if (buffer == null) {
do {
ch = reader.read();
} while ((ch == ' ') || (ch == '\t') || (ch == '\n'));
} else {
for (;;) {
ch = reader.read();
if ((ch != ' ') && (ch != '\t') && (ch != '\n')) {
break;
}
if (ch == '\n') {
buffer.append('\n');
} else {
buffer.append(' ');
}
}
}
reader.unread(ch);
}
// in java/net/n3/nanoxml/XMLUtil.java
static String read(IXMLReader reader,
char entityChar)
throws IOException,
XMLParseException
{
char ch = reader.read();
StringBuffer buf = new StringBuffer();
buf.append(ch);
if (ch == entityChar) {
while (ch != ';') {
ch = reader.read();
buf.append(ch);
}
}
return buf.toString();
}
// in java/net/n3/nanoxml/XMLUtil.java
static char readChar(IXMLReader reader,
char entityChar)
throws IOException,
XMLParseException
{
String str = XMLUtil.read(reader, entityChar);
char ch = str.charAt(0);
if (ch == entityChar) {
XMLUtil.errorUnexpectedEntity(reader.getSystemID(),
reader.getLineNr(),
str);
}
return ch;
}
// in java/net/n3/nanoxml/XMLUtil.java
static boolean checkLiteral(IXMLReader reader,
String literal)
throws IOException,
XMLParseException
{
for (int i = 0; i < literal.length(); i++) {
if (reader.read() != literal.charAt(i)) {
return false;
}
}
return true;
}
// in java/net/n3/nanoxml/XMLWriter.java
public void write(IXMLElement xml)
throws IOException
{
this.write(xml, false, 0, true);
}
// in java/net/n3/nanoxml/XMLWriter.java
public void write(IXMLElement xml,
boolean prettyPrint)
throws IOException
{
this.write(xml, prettyPrint, 0, true);
}
// in java/net/n3/nanoxml/XMLWriter.java
public void write(IXMLElement xml,
boolean prettyPrint,
int indent)
throws IOException
{
this.write(xml, prettyPrint, indent, true);
}
// in java/net/n3/nanoxml/XMLWriter.java
public void write(IXMLElement xml,
boolean prettyPrint,
int indent,
boolean collapseEmptyElements)
throws IOException
{
if (prettyPrint) {
for (int i = 0; i < indent; i++) {
this.writer.print(' ');
}
}
if (xml.getName() == null) {
if (xml.getContent() != null) {
if (prettyPrint) {
this.writeEncoded(xml.getContent().trim());
writer.println();
} else {
this.writeEncoded(xml.getContent());
}
}
} else {
this.writer.print('<');
this.writer.print(xml.getFullName());
Vector nsprefixes = new Vector();
if (xml.getNamespace() != null) {
if (xml.getName().equals(xml.getFullName())) {
this.writer.print(" xmlns=\"" + xml.getNamespace() + '"');
} else {
String prefix = xml.getFullName();
prefix = prefix.substring(0, prefix.indexOf(':'));
nsprefixes.addElement(prefix);
this.writer.print(" xmlns:" + prefix);
this.writer.print("=\"" + xml.getNamespace() + "\"");
}
}
Iterator enm = xml.iterateAttributeNames();
while (enm.hasNext()) {
String key = (String) enm.next();
int index = key.indexOf(':');
if (index >= 0) {
String namespace = xml.getAttributeNamespace(key);
if (namespace != null) {
String prefix = key.substring(0, index);
if (! nsprefixes.contains(prefix)) {
this.writer.print(" xmlns:" + prefix);
this.writer.print("=\"" + namespace + '"');
nsprefixes.addElement(prefix);
}
}
}
}
enm = xml.iterateAttributeNames();
while (enm.hasNext()) {
String key = (String) enm.next();
String value = xml.getAttribute(key, null);
this.writer.print(" " + key + "=\"");
this.writeEncoded(value);
this.writer.print('"');
}
if ((xml.getContent() != null)
&& (xml.getContent().length() > 0)) {
writer.print('>');
this.writeEncoded(xml.getContent());
writer.print("</" + xml.getFullName() + '>');
if (prettyPrint) {
writer.println();
}
} else if (xml.hasChildren() || (! collapseEmptyElements)) {
writer.print('>');
if (prettyPrint) {
writer.println();
}
enm = xml.iterateChildren();
while (enm.hasNext()) {
IXMLElement child = (IXMLElement) enm.next();
this.write(child, prettyPrint, indent + 4,
collapseEmptyElements);
}
if (prettyPrint) {
for (int i = 0; i < indent; i++) {
this.writer.print(' ');
}
}
this.writer.print("</" + xml.getFullName() + ">");
if (prettyPrint) {
writer.println();
}
} else {
this.writer.print("/>");
if (prettyPrint) {
writer.println();
}
}
}
this.writer.flush();
}
// in java/net/n3/nanoxml/StdXMLReader.java
public static IXMLReader fileReader(String filename)
throws FileNotFoundException,
IOException
{
StdXMLReader r = new StdXMLReader(new FileInputStream(filename));
r.setSystemID(filename);
for (int i = 0; i < r.readers.size(); i++) {
StackedReader sr = (StackedReader) r.readers.elementAt(i);
sr.systemId = r.currentReader.systemId;
}
return r;
}
// in java/net/n3/nanoxml/StdXMLReader.java
protected Reader stream2reader(InputStream stream,
StringBuffer charsRead)
throws IOException
{
PushbackInputStream pbstream = new PushbackInputStream(stream);
int b = pbstream.read();
switch (b) {
case 0x00:
case 0xFE:
case 0xFF:
pbstream.unread(b);
return new InputStreamReader(pbstream, "UTF-16");
case 0xEF:
for (int i = 0; i < 2; i++) {
pbstream.read();
}
return new InputStreamReader(pbstream, "UTF-8");
case 0x3C:
b = pbstream.read();
charsRead.append('<');
while ((b > 0) && (b != 0x3E)) {
charsRead.append((char) b);
b = pbstream.read();
}
if (b > 0) {
charsRead.append((char) b);
}
String encoding = this.getEncoding(charsRead.toString());
if (encoding == null) {
return new InputStreamReader(pbstream, "UTF-8");
}
charsRead.setLength(0);
try {
return new InputStreamReader(pbstream, encoding);
} catch (UnsupportedEncodingException e) {
return new InputStreamReader(pbstream, "UTF-8");
}
default:
charsRead.append((char) b);
return new InputStreamReader(pbstream, "UTF-8");
}
}
// in java/net/n3/nanoxml/StdXMLReader.java
public char read()
throws IOException
{
int ch = this.currentReader.pbReader.read();
while (ch < 0) {
if (this.readers.empty()) {
throw new IOException("Unexpected EOF");
}
this.currentReader.pbReader.close();
this.currentReader = (StackedReader) this.readers.pop();
ch = this.currentReader.pbReader.read();
}
return (char) ch;
}
// in java/net/n3/nanoxml/StdXMLReader.java
public boolean atEOFOfCurrentStream()
throws IOException
{
int ch = this.currentReader.pbReader.read();
if (ch < 0) {
return true;
} else {
this.currentReader.pbReader.unread(ch);
return false;
}
}
// in java/net/n3/nanoxml/StdXMLReader.java
public boolean atEOF()
throws IOException
{
int ch = this.currentReader.pbReader.read();
while (ch < 0) {
if (this.readers.empty()) {
return true;
}
this.currentReader.pbReader.close();
this.currentReader = (StackedReader) this.readers.pop();
ch = this.currentReader.pbReader.read();
}
this.currentReader.pbReader.unread(ch);
return false;
}
// in java/net/n3/nanoxml/StdXMLReader.java
public void unread(char ch)
throws IOException
{
this.currentReader.pbReader.unread(ch);
}
// in java/net/n3/nanoxml/StdXMLReader.java
public Reader openStream(String publicID,
String systemID)
throws MalformedURLException,
FileNotFoundException,
IOException
{
URL url = new URL(this.currentReader.systemId, systemID);
if (url.getRef() != null) {
String ref = url.getRef();
if (url.getFile().length() > 0) {
url = new URL(url.getProtocol(), url.getHost(), url.getPort(),
url.getFile());
url = new URL("jar:" + url + '!' + ref);
} else {
url = StdXMLReader.class.getResource(ref);
}
}
this.currentReader.publicId = publicID;
this.currentReader.systemId = url;
StringBuffer charsRead = new StringBuffer();
Reader reader = this.stream2reader(url.openStream(), charsRead);
if (charsRead.length() == 0) {
return reader;
}
String charsReadStr = charsRead.toString();
PushbackReader pbreader = new PushbackReader(reader,
charsReadStr.length());
for (int i = charsReadStr.length() - 1; i >= 0; i--) {
pbreader.unread(charsReadStr.charAt(i));
}
return pbreader;
}
// in java/net/n3/nanoxml/ContentReader.java
public int read(char[] outputBuffer,
int offset,
int size)
throws IOException
{
try {
int charsRead = 0;
int bufferLength = this.buffer.length();
if ((offset + size) > outputBuffer.length) {
size = outputBuffer.length - offset;
}
while (charsRead < size) {
String str = "";
char ch;
if (this.bufferIndex >= bufferLength) {
str = XMLUtil.read(this.reader, '&');
ch = str.charAt(0);
} else {
ch = this.buffer.charAt(this.bufferIndex);
this.bufferIndex++;
outputBuffer[charsRead] = ch;
charsRead++;
continue; // don't interprete chars in the buffer
}
if (ch == '<') {
this.reader.unread(ch);
break;
}
if ((ch == '&') && (str.length() > 1)) {
if (str.charAt(1) == '#') {
ch = XMLUtil.processCharLiteral(str);
} else {
XMLUtil.processEntity(str, this.reader, this.resolver);
continue;
}
}
outputBuffer[charsRead] = ch;
charsRead++;
}
if (charsRead == 0) {
charsRead = -1;
}
return charsRead;
} catch (XMLParseException e) {
throw new IOException(e.getMessage());
}
}
// in java/net/n3/nanoxml/ContentReader.java
public void close()
throws IOException
{
try {
int bufferLength = this.buffer.length();
for (;;) {
String str = "";
char ch;
if (this.bufferIndex >= bufferLength) {
str = XMLUtil.read(this.reader, '&');
ch = str.charAt(0);
} else {
ch = this.buffer.charAt(this.bufferIndex);
this.bufferIndex++;
continue; // don't interprete chars in the buffer
}
if (ch == '<') {
this.reader.unread(ch);
break;
}
if ((ch == '&') && (str.length() > 1)) {
if (str.charAt(1) != '#') {
XMLUtil.processEntity(str, this.reader, this.resolver);
}
}
}
} catch (XMLParseException e) {
throw new IOException(e.getMessage());
}
}
// in java/net/n3/nanoxml/PIReader.java
public int read(char[] buffer,
int offset,
int size)
throws IOException
{
if (this.atEndOfData) {
return -1;
}
int charsRead = 0;
if ((offset + size) > buffer.length) {
size = buffer.length - offset;
}
while (charsRead < size) {
char ch = this.reader.read();
if (ch == '?') {
char ch2 = this.reader.read();
if (ch2 == '>') {
this.atEndOfData = true;
break;
}
this.reader.unread(ch2);
}
buffer[charsRead] = ch;
charsRead++;
}
if (charsRead == 0) {
charsRead = -1;
}
return charsRead;
}
// in java/net/n3/nanoxml/PIReader.java
public void close()
throws IOException
{
while (! this.atEndOfData) {
char ch = this.reader.read();
if (ch == '?') {
char ch2 = this.reader.read();
if (ch2 == '>') {
this.atEndOfData = true;
}
}
}
}
// in java/net/n3/nanoxml/CDATAReader.java
public int read(char[] buffer,
int offset,
int size)
throws IOException
{
int charsRead = 0;
if (this.atEndOfData) {
return -1;
}
if ((offset + size) > buffer.length) {
size = buffer.length - offset;
}
while (charsRead < size) {
char ch = this.savedChar;
if (ch == 0) {
ch = this.reader.read();
} else {
this.savedChar = 0;
}
if (ch == ']') {
char ch2 = this.reader.read();
if (ch2 == ']') {
char ch3 = this.reader.read();
if (ch3 == '>') {
this.atEndOfData = true;
break;
}
this.savedChar = ch2;
this.reader.unread(ch3);
} else {
this.reader.unread(ch2);
}
}
buffer[charsRead] = ch;
charsRead++;
}
if (charsRead == 0) {
charsRead = -1;
}
return charsRead;
}
// in java/net/n3/nanoxml/CDATAReader.java
public void close()
throws IOException
{
while (! this.atEndOfData) {
char ch = this.savedChar;
if (ch == 0) {
ch = this.reader.read();
} else {
this.savedChar = 0;
}
if (ch == ']') {
char ch2 = this.reader.read();
if (ch2 == ']') {
char ch3 = this.reader.read();
if (ch3 == '>') {
break;
}
this.savedChar = ch2;
this.reader.unread(ch3);
} else {
this.reader.unread(ch2);
}
}
}
this.atEndOfData = true;
}
// in java/org/jhotdraw/gui/datatransfer/ImageTransferable.java
Override
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
/*if (! isDataFlavorSupported(flavor)) {
throw new UnsupportedFlavorException(flavor);
}*/
if (flavor.equals(DataFlavor.imageFlavor)) {
return image;
} else if (flavor.equals(IMAGE_PNG_FLAVOR)) {
ByteArrayOutputStream buf = new ByteArrayOutputStream();
ImageIO.write(Images.toBufferedImage(image), "PNG", buf);
return new ByteArrayInputStream(buf.toByteArray());
} else {
throw new UnsupportedFlavorException(flavor);
}
}
// in java/org/jhotdraw/gui/datatransfer/InputStreamTransferable.java
Override
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
if (! isDataFlavorSupported(flavor)) {
throw new UnsupportedFlavorException(flavor);
}
return new ByteArrayInputStream(data);
}
// in java/org/jhotdraw/gui/datatransfer/CompositeTransferable.java
Override
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
Transferable t = (Transferable) transferables.get(flavor);
if (t == null) throw new UnsupportedFlavorException(flavor);
return t.getTransferData(flavor);
}
// in java/org/jhotdraw/xml/JavaPrimitivesDOMFactory.java
Override
public void write(DOMOutput out, Object o) throws IOException {
if (o == null) {
// nothing to do
} else if (o instanceof DOMStorable) {
((DOMStorable) o).write(out);
} else if (o instanceof String) {
out.addText((String) o);
} else if (o instanceof Integer) {
out.addText(o.toString());
} else if (o instanceof Long) {
out.addText(o.toString());
} else if (o instanceof Double) {
out.addText(o.toString());
} else if (o instanceof Float) {
out.addText(o.toString());
} else if (o instanceof Boolean) {
out.addText(o.toString());
} else if (o instanceof Color) {
Color c = (Color) o;
out.addAttribute("rgba", "#" + Integer.toHexString(c.getRGB()));
} else if (o instanceof byte[]) {
byte[] a = (byte[]) o;
for (int i = 0; i < a.length; i++) {
out.openElement("byte");
write(out, a[i]);
out.closeElement();
}
} else if (o instanceof boolean[]) {
boolean[] a = (boolean[]) o;
for (int i = 0; i < a.length; i++) {
out.openElement("boolean");
write(out, a[i]);
out.closeElement();
}
} else if (o instanceof char[]) {
char[] a = (char[]) o;
for (int i = 0; i < a.length; i++) {
out.openElement("char");
write(out, a[i]);
out.closeElement();
}
} else if (o instanceof short[]) {
short[] a = (short[]) o;
for (int i = 0; i < a.length; i++) {
out.openElement("short");
write(out, a[i]);
out.closeElement();
}
} else if (o instanceof int[]) {
int[] a = (int[]) o;
for (int i = 0; i < a.length; i++) {
out.openElement("int");
write(out, a[i]);
out.closeElement();
}
} else if (o instanceof long[]) {
long[] a = (long[]) o;
for (int i = 0; i < a.length; i++) {
out.openElement("long");
write(out, a[i]);
out.closeElement();
}
} else if (o instanceof float[]) {
float[] a = (float[]) o;
for (int i = 0; i < a.length; i++) {
out.openElement("float");
write(out, a[i]);
out.closeElement();
}
} else if (o instanceof double[]) {
double[] a = (double[]) o;
for (int i = 0; i < a.length; i++) {
out.openElement("double");
write(out, a[i]);
out.closeElement();
}
} else if (o instanceof Font) {
Font f = (Font) o;
out.addAttribute("name", f.getName());
out.addAttribute("style", f.getStyle());
out.addAttribute("size", f.getSize());
} else if (o instanceof Enum) {
Enum e = (Enum) o;
out.addAttribute("type", getEnumName(e));
out.addText(getEnumValue(e));
} else {
throw new IllegalArgumentException("Unsupported object type:" + o);
}
}
// in java/org/jhotdraw/xml/JavaxDOMOutput.java
protected void reset() throws IOException {
try {
objectids = new HashMap<Object,String>();
document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
current = document;
} catch (ParserConfigurationException e) {
IOException error = new IOException(e.getMessage());
error.initCause(e);
throw error;
}
}
// in java/org/jhotdraw/xml/JavaxDOMOutput.java
public void save(OutputStream out) throws IOException {
reset();
try {
if (doctype != null) {
OutputStreamWriter w = new OutputStreamWriter(out, "UTF8");
w.write("<!DOCTYPE ");
w.write(doctype);
w.write(">\n");
w.flush();
}
Transformer t = TransformerFactory.newInstance().newTransformer();
t.transform(new DOMSource(document), new StreamResult(out));
} catch (TransformerException e) {
IOException error = new IOException(e.getMessage());
error.initCause(e);
throw error;
}
}
// in java/org/jhotdraw/xml/JavaxDOMOutput.java
public void save(Writer out) throws IOException {
reset();
try {
if (doctype != null) {
out.write("<!DOCTYPE ");
out.write(doctype);
out.write(">\n");
}
Transformer t = TransformerFactory.newInstance().newTransformer();
t.transform(new DOMSource(document), new StreamResult(out));
} catch (TransformerException e) {
IOException error = new IOException(e.getMessage());
error.initCause(e);
throw error;
}
}
// in java/org/jhotdraw/xml/JavaxDOMOutput.java
Override
public void writeObject(Object o) throws IOException {
String tagName = factory.getName(o);
if (tagName == null) throw new IllegalArgumentException("no tag name for:"+o);
openElement(tagName);
if (objectids.containsKey(o)) {
addAttribute("ref", (String) objectids.get(o));
} else {
String id = Integer.toString(objectids.size(), 16);
objectids.put(o, id);
addAttribute("id", id);
factory.write(this,o);
}
closeElement();
}
// in java/org/jhotdraw/xml/NanoXMLDOMOutput.java
public void save(OutputStream out) throws IOException {
Writer w = new OutputStreamWriter(out, "UTF8");
save(w);
w.flush();
}
// in java/org/jhotdraw/xml/NanoXMLDOMOutput.java
public void save(Writer out) throws IOException {
if (doctype != null) {
out.write("<!DOCTYPE ");
out.write(doctype);
out.write(">\n");
}
XMLWriter writer = new XMLWriter(out);
writer.write((XMLElement) document.getChildren().get(0));
}
// in java/org/jhotdraw/xml/NanoXMLDOMOutput.java
Override
public void writeObject(Object o) throws IOException {
String tagName = factory.getName(o);
if (tagName == null) throw new IllegalArgumentException("no tag name for:"+o);
openElement(tagName);
XMLElement element = current;
if (objectids.containsKey(o)) {
addAttribute("ref", (String) objectids.get(o));
} else {
String id = Integer.toString(objectids.size(), 16);
objectids.put(o, id);
addAttribute("id", id);
factory.write(this,o);
}
closeElement();
}
// in java/org/jhotdraw/xml/XMLTransferable.java
Override
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
if (this.flavor.equals(flavor)) {
return new ByteArrayInputStream(data);
} else {
throw new UnsupportedFlavorException(flavor);
}
}
// in java/org/jhotdraw/xml/NanoXMLDOMInput.java
Override
public void openElement(String tagName) throws IOException {
ArrayList list = current.getChildren();
for (int i=0; i < list.size(); i++) {
XMLElement node = (XMLElement) list.get(i);
if (node.getName().equals(tagName)) {
stack.push(current);
current = node;
return;
}
}
throw new IOException("no such element:"+tagName);
}
// in java/org/jhotdraw/xml/NanoXMLDOMInput.java
Override
public void openElement(String tagName, int index) throws IOException {
int count = 0;
ArrayList list = current.getChildren();
for (int i=0; i < list.size(); i++) {
XMLElement node = (XMLElement) list.get(i);
if (node.getName().equals(tagName)) {
if (count++ == index) {
stack.push(current);
current = node;
return;
}
}
}
throw new IOException("no such element:"+tagName+" at index:"+index);
}
// in java/org/jhotdraw/xml/NanoXMLDOMInput.java
Override
public Object readObject() throws IOException {
return readObject(0);
}
// in java/org/jhotdraw/xml/NanoXMLDOMInput.java
Override
public Object readObject(int index) throws IOException {
openElement(index);
Object o;
String ref = getAttribute("ref", null);
String id = getAttribute("id", null);
if (ref != null && id != null) {
throw new IOException("Element has both an id and a ref attribute: <" + getTagName() + " id=\"" + id + "\" ref=\"" + ref + "\"> in line number "+current.getLineNr());
}
if (id != null && idobjects.containsKey(id)) {
throw new IOException("Duplicate id attribute: <" + getTagName() + " id=\"" + id + "\"> in line number "+current.getLineNr());
}
if (ref != null && !idobjects.containsKey(ref)) {
throw new IOException("Referenced element not found: <" + getTagName() + " ref=\"" + ref + "\"> in line number "+current.getLineNr());
}
// Keep track of objects which have an ID
if (ref != null) {
o = idobjects.get(ref);
} else {
o = factory.read(this);
if (id != null) {
idobjects.put(id, o);
}
if (o instanceof DOMStorable) {
((DOMStorable) o).read(this);
}
}
closeElement();
return o;
}
// in java/org/jhotdraw/xml/css/CSSParser.java
public void parse(String css, StyleManager rm) throws IOException {
parse(new StringReader(css), rm);
}
// in java/org/jhotdraw/xml/css/CSSParser.java
public void parse(Reader css, StyleManager rm) throws IOException {
StreamTokenizer tt = new StreamTokenizer(css);
tt.resetSyntax();
tt.wordChars('a', 'z');
tt.wordChars('A', 'Z');
tt.wordChars('0', '9');
tt.wordChars(128 + 32, 255);
tt.whitespaceChars(0, ' ');
tt.commentChar('/');
tt.slashStarComments(true);
parseStylesheet(tt, rm);
}
// in java/org/jhotdraw/xml/css/CSSParser.java
private void parseStylesheet(StreamTokenizer tt, StyleManager rm) throws IOException {
while (tt.nextToken() != StreamTokenizer.TT_EOF) {
tt.pushBack();
parseRuleset(tt, rm);
}
}
// in java/org/jhotdraw/xml/css/CSSParser.java
private void parseRuleset(StreamTokenizer tt, StyleManager rm) throws IOException {
// parse selector list
List<String> selectors = parseSelectorList(tt);
if (tt.nextToken() != '{') throw new IOException("Ruleset '{' missing for "+selectors);
Map<String,String> declarations = parseDeclarationMap(tt);
if (tt.nextToken() != '}') throw new IOException("Ruleset '}' missing for "+selectors);
for (String selector : selectors) {
rm.add(new CSSRule(selector, declarations));
// System.out.println("CSSParser.add("+selector+","+declarations);
/*
for (Map.Entry<String,String> entry : declarations.entrySet()) {
rm.add(new CSSRule(selector, entry.getKey(), entry.getValue()));
}*/
}
}
// in java/org/jhotdraw/xml/css/CSSParser.java
private List<String> parseSelectorList(StreamTokenizer tt) throws IOException {
LinkedList<String> list = new LinkedList<String>();
StringBuilder selector = new StringBuilder();
boolean needsWhitespace = false;
while (tt.nextToken() != StreamTokenizer.TT_EOF &&
tt.ttype != '{') {
switch (tt.ttype) {
case StreamTokenizer.TT_WORD :
if (needsWhitespace) selector.append(' ');
selector.append(tt.sval);
needsWhitespace = true;
break;
case ',' :
list.add(selector.toString());
selector.setLength(0);
needsWhitespace = false;
break;
default :
if (needsWhitespace) selector.append(' ');
selector.append((char) tt.ttype);
needsWhitespace = false;
break;
}
}
if (selector.length() != 0) {
list.add(selector.toString());
}
tt.pushBack();
//System.out.println("selectors:"+list);
return list;
}
// in java/org/jhotdraw/xml/css/CSSParser.java
private Map<String,String> parseDeclarationMap(StreamTokenizer tt) throws IOException {
HashMap<String,String> map = new HashMap<String, String>();
do {
// Parse key
StringBuilder key = new StringBuilder();
while (tt.nextToken() != StreamTokenizer.TT_EOF &&
tt.ttype != '}' && tt.ttype != ':' && tt.ttype != ';') {
switch (tt.ttype) {
case StreamTokenizer.TT_WORD :
key.append(tt.sval);
break;
default :
key.append((char) tt.ttype);
break;
}
}
if (tt.ttype == '}' && key.length() == 0) { break; }
if (tt.ttype != ':') throw new IOException("Declaration ':' missing for "+key);
// Parse value
StringBuilder value = new StringBuilder();
boolean needsWhitespace = false;
while (tt.nextToken() != StreamTokenizer.TT_EOF &&
tt.ttype != ';' && tt.ttype != '}') {
switch (tt.ttype) {
case StreamTokenizer.TT_WORD :
if (needsWhitespace) value.append(' ');
value.append(tt.sval);
needsWhitespace = true;
break;
default :
value.append((char) tt.ttype);
needsWhitespace = false;
break;
}
}
map.put(key.toString(), value.toString());
//System.out.println(" declaration: "+key+":"+value);
} while (tt.ttype != '}' && tt.ttype != StreamTokenizer.TT_EOF);
tt.pushBack();
return map;
}
// in java/org/jhotdraw/xml/JavaxDOMInput.java
protected static DocumentBuilder getBuilder() throws IOException {
if (documentBuilder == null) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(false);
factory.setXIncludeAware(false);
try {
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
documentBuilder = factory.newDocumentBuilder();
} catch (Exception ex) {
InternalError error = new InternalError("Unable to create DocumentBuilder");
error.initCause(ex);
throw error;
}
}
return documentBuilder;
}
// in java/org/jhotdraw/xml/JavaxDOMInput.java
Override
public Object readObject() throws IOException {
return readObject(0);
}
// in java/org/jhotdraw/xml/JavaxDOMInput.java
Override
public Object readObject(int index) throws IOException {
openElement(index);
Object o;
String ref = getAttribute("ref", null);
String id = getAttribute("id", null);
if (ref != null && id != null) {
throw new IOException("Element has both an id and a ref attribute: <" + getTagName() + " id=" + id + " ref=" + ref + ">");
}
if (id != null && idobjects.containsKey(id)) {
throw new IOException("Duplicate id attribute: <" + getTagName() + " id=" + id + ">");
}
if (ref != null && !idobjects.containsKey(ref)) {
throw new IOException("Illegal ref attribute value: <" + getTagName() + " ref=" + ref + ">");
}
// Keep track of objects which have an ID
if (ref != null) {
o = idobjects.get(ref);
} else {
o = factory.read(this);
if (id != null) {
idobjects.put(id, o);
}
if (o instanceof DOMStorable) {
((DOMStorable) o).read(this);
}
}
closeElement();
return o;
}
// in java/org/jhotdraw/net/ClientHttpRequest.java
protected void connect() throws IOException {
if (os == null) {
os = connection.getOutputStream();
}
}
// in java/org/jhotdraw/net/ClientHttpRequest.java
protected void write(char c) throws IOException {
connect();
os.write(c);
}
// in java/org/jhotdraw/net/ClientHttpRequest.java
protected void write(String s) throws IOException {
connect();
// BEGIN PATCH W. Randelshofer 2008-05-23 use UTF-8
os.write(s.getBytes("UTF-8"));
// END PATCH W. Randelshofer 2008-05-23 use UTF-8
}
// in java/org/jhotdraw/net/ClientHttpRequest.java
protected void newline() throws IOException {
connect();
write("\r\n");
}
// in java/org/jhotdraw/net/ClientHttpRequest.java
protected void writeln(String s) throws IOException {
connect();
write(s);
newline();
}
// in java/org/jhotdraw/net/ClientHttpRequest.java
private void boundary() throws IOException {
write("--");
write(boundary);
}
// in java/org/jhotdraw/net/ClientHttpRequest.java
public void setCookies(String rawCookies) throws IOException {
this.rawCookies = (rawCookies == null) ? "" : rawCookies;
cookies.clear();
}
// in java/org/jhotdraw/net/ClientHttpRequest.java
public void setCookie(String name, String value) throws IOException {
cookies.put(name, value);
}
// in java/org/jhotdraw/net/ClientHttpRequest.java
public void setCookies(Map<String, String> cookies) throws IOException {
if (cookies == null) {
return;
}
this.cookies.putAll(cookies);
}
// in java/org/jhotdraw/net/ClientHttpRequest.java
public void setCookies(String[] cookies) throws IOException {
if (cookies == null) {
return;
}
for (int i = 0; i < cookies.length - 1; i += 2) {
setCookie(cookies[i], cookies[i + 1]);
}
}
// in java/org/jhotdraw/net/ClientHttpRequest.java
private void writeName(String name) throws IOException {
newline();
write("Content-Disposition: form-data; name=\"");
write(name);
write('"');
}
// in java/org/jhotdraw/net/ClientHttpRequest.java
public void setParameter(String name, String value) throws IOException {
if (name == null) {
throw new InvalidParameterException("setParameter(" + name + "," + value + ") name must not be null");
}
if (value == null) {
throw new InvalidParameterException("setParameter(" + name + "," + value + ") value must not be null");
}
boundary();
writeName(name);
newline();
newline();
writeln(value);
}
// in java/org/jhotdraw/net/ClientHttpRequest.java
private static void pipe(InputStream in, OutputStream out) throws IOException {
byte[] buf = new byte[500000];
int nread;
int total = 0;
synchronized (in) {
while ((nread = in.read(buf, 0, buf.length)) >= 0) {
out.write(buf, 0, nread);
total += nread;
}
}
out.flush();
buf = null;
}
// in java/org/jhotdraw/net/ClientHttpRequest.java
public void setParameter(String name, String filename, InputStream is) throws IOException {
boundary();
writeName(name);
write("; filename=\"");
write(filename);
write('"');
newline();
write("Content-Type: ");
String type = URLConnection.guessContentTypeFromName(filename);
if (type == null) {
type = "application/octet-stream";
}
writeln(type);
newline();
pipe(is, os);
newline();
}
// in java/org/jhotdraw/net/ClientHttpRequest.java
public void setParameter(String name, File file) throws IOException {
FileInputStream in = new FileInputStream(file);
try {
setParameter(name, file.getPath(), in);
} finally {
in.close();
}
}
// in java/org/jhotdraw/net/ClientHttpRequest.java
public void setParameter(String name, Object object) throws IOException {
if (object instanceof File) {
setParameter(name, (File) object);
} else {
setParameter(name, object.toString());
}
}
// in java/org/jhotdraw/net/ClientHttpRequest.java
public void setParameters(Map parameters) throws IOException {
if (parameters != null) {
for (Iterator i = parameters.entrySet().iterator(); i.hasNext();) {
Map.Entry entry = (Map.Entry) i.next();
setParameter(entry.getKey().toString(), entry.getValue());
}
}
}
// in java/org/jhotdraw/net/ClientHttpRequest.java
public void setParameters(Object[] parameters) throws IOException {
if (parameters != null) {
for (int i = 0; i < parameters.length - 1; i += 2) {
setParameter(parameters[i].toString(), parameters[i + 1]);
}
}
}
// in java/org/jhotdraw/net/ClientHttpRequest.java
private InputStream doPost() throws IOException {
boundary();
writeln("--");
os.close();
return connection.getInputStream();
}
// in java/org/jhotdraw/net/ClientHttpRequest.java
public InputStream post() throws IOException {
postCookies();
return doPost();
}
// in java/org/jhotdraw/net/ClientHttpRequest.java
public InputStream post(Map parameters) throws IOException {
postCookies();
setParameters(parameters);
return doPost();
}
// in java/org/jhotdraw/net/ClientHttpRequest.java
public InputStream post(Object[] parameters) throws IOException {
postCookies();
setParameters(parameters);
return doPost();
}
// in java/org/jhotdraw/net/ClientHttpRequest.java
public InputStream post(Map<String, String> cookies, Map parameters) throws IOException {
setCookies(cookies);
postCookies();
setParameters(parameters);
return doPost();
}
// in java/org/jhotdraw/net/ClientHttpRequest.java
public InputStream post(String raw_cookies, Map parameters) throws IOException {
setCookies(raw_cookies);
postCookies();
setParameters(parameters);
return doPost();
}
// in java/org/jhotdraw/net/ClientHttpRequest.java
public InputStream post(String[] cookies, Object[] parameters) throws IOException {
setCookies(cookies);
postCookies();
setParameters(parameters);
return doPost();
}
// in java/org/jhotdraw/net/ClientHttpRequest.java
public InputStream post(String name, Object value) throws IOException {
postCookies();
setParameter(name, value);
return doPost();
}
// in java/org/jhotdraw/net/ClientHttpRequest.java
public InputStream post(String name1, Object value1, String name2, Object value2) throws IOException {
postCookies();
setParameter(name1, value1);
setParameter(name2, value2);
return doPost();
}
// in java/org/jhotdraw/net/ClientHttpRequest.java
public InputStream post(String name1, Object value1, String name2, Object value2, String name3, Object value3) throws IOException {
postCookies();
setParameter(name1, value1);
setParameter(name2, value2);
setParameter(name3, value3);
return doPost();
}
// in java/org/jhotdraw/net/ClientHttpRequest.java
public InputStream post(String name1, Object value1, String name2, Object value2, String name3, Object value3, String name4, Object value4) throws IOException {
postCookies();
setParameter(name1, value1);
setParameter(name2, value2);
setParameter(name3, value3);
setParameter(name4, value4);
return doPost();
}
// in java/org/jhotdraw/net/ClientHttpRequest.java
public static InputStream post(URL url, Map parameters) throws IOException {
return new ClientHttpRequest(url).post(parameters);
}
// in java/org/jhotdraw/net/ClientHttpRequest.java
public static InputStream post(URL url, Object[] parameters) throws IOException {
return new ClientHttpRequest(url).post(parameters);
}
// in java/org/jhotdraw/net/ClientHttpRequest.java
public static InputStream post(URL url, Map<String, String> cookies, Map parameters) throws IOException {
return new ClientHttpRequest(url).post(cookies, parameters);
}
// in java/org/jhotdraw/net/ClientHttpRequest.java
public static InputStream post(URL url, String[] cookies, Object[] parameters) throws IOException {
return new ClientHttpRequest(url).post(cookies, parameters);
}
// in java/org/jhotdraw/net/ClientHttpRequest.java
public static InputStream post(URL url, String name1, Object value1) throws IOException {
return new ClientHttpRequest(url).post(name1, value1);
}
// in java/org/jhotdraw/net/ClientHttpRequest.java
public static InputStream post(URL url, String name1, Object value1, String name2, Object value2) throws IOException {
return new ClientHttpRequest(url).post(name1, value1, name2, value2);
}
// in java/org/jhotdraw/net/ClientHttpRequest.java
public static InputStream post(URL url, String name1, Object value1, String name2, Object value2, String name3, Object value3) throws IOException {
return new ClientHttpRequest(url).post(name1, value1, name2, value2, name3, value3);
}
// in java/org/jhotdraw/net/ClientHttpRequest.java
public static InputStream post(URL url, String name1, Object value1, String name2, Object value2, String name3, Object value3, String name4, Object value4) throws IOException {
return new ClientHttpRequest(url).post(name1, value1, name2, value2, name3, value3, name4, value4);
}
// in java/org/jhotdraw/io/Base64.java
Override
public int read() throws java.io.IOException {
// Do we need to get data?
if (position < 0) {
if (encode) {
byte[] b3 = new byte[3];
int numBinaryBytes = 0;
for (int i = 0; i < 3; i++) {
try {
int b = in.read();
// If end of stream, b is -1.
if (b >= 0) {
b3[i] = (byte) b;
numBinaryBytes++;
} // end if: not end of stream
} // end try: read
catch (java.io.IOException e) {
// Only a problem if we got no data at all.
if (i == 0) {
throw e;
}
} // end catch
} // end for: each needed input byte
if (numBinaryBytes > 0) {
encode3to4(b3, 0, numBinaryBytes, buffer, 0);
position = 0;
numSigBytes = 4;
} // end if: got data
else {
return -1;
} // end else
} // end if: encoding
// Else decoding
else {
byte[] b4 = new byte[4];
int i = 0;
for (i = 0; i < 4; i++) {
// Read four "meaningful" bytes:
int b = 0;
do {
b = in.read();
} while (b >= 0 && DECODABET[b & 0x7f] <= WHITE_SPACE_ENC);
if (b < 0) {
break; // Reads a -1 if end of stream
}
b4[i] = (byte) b;
} // end for: each needed input byte
if (i == 4) {
numSigBytes = decode4to3(b4, 0, buffer, 0);
position = 0;
} // end if: got four characters
else if (i == 0) {
return -1;
} // end else if: also padded correctly
else {
// Must have broken out from above.
throw new java.io.IOException("Improperly padded Base64 input.");
} // end
} // end else: decode
} // end else: get data
// Got data?
if (position >= 0) {
// End of relevant data?
if ( /*!encode &&*/position >= numSigBytes) {
return -1;
}
if (encode && breakLines && lineLength >= MAX_LINE_LENGTH) {
lineLength = 0;
return '\n';
} // end if
else {
lineLength++; // This isn't important when decoding
// but throwing an extra "if" seems
// just as wasteful.
int b = buffer[position++];
if (position >= bufferLength) {
position = -1;
}
return b & 0xFF; // This is how you "cast" a byte that's
// intended to be unsigned.
} // end else
} // end if: position >= 0
// Else error
else {
// When JDK1.4 is more accepted, use an assertion here.
throw new java.io.IOException("Error in Base64 code reading stream.");
} // end else
}
// in java/org/jhotdraw/io/Base64.java
Override
public int read(byte[] dest, int off, int len) throws java.io.IOException {
int i;
int b;
for (i = 0; i < len; i++) {
b = read();
//if( b < 0 && i == 0 )
// return -1;
if (b >= 0) {
dest[off + i] = (byte) b;
} else if (i == 0) {
return -1;
} else {
break; // Out of 'for' loop
}
} // end for: each byte read
return i;
}
// in java/org/jhotdraw/io/Base64.java
Override
public void write(int theByte) throws java.io.IOException {
// Encoding suspended?
if (suspendEncoding) {
super.out.write(theByte);
return;
} // end if: supsended
// Encode?
if (encode) {
buffer[position++] = (byte) theByte;
if (position >= bufferLength) // Enough to encode.
{
out.write(encode3to4(b4, buffer, bufferLength));
lineLength += 4;
if (breakLines && lineLength >= MAX_LINE_LENGTH) {
out.write(NEW_LINE);
lineLength = 0;
} // end if: end of line
position = 0;
} // end if: enough to output
} // end if: encoding
// Else, Decoding
else {
// Meaningful Base64 character?
if (DECODABET[theByte & 0x7f] > WHITE_SPACE_ENC) {
buffer[position++] = (byte) theByte;
if (position >= bufferLength) // Enough to output.
{
int len = Base64.decode4to3(buffer, 0, b4, 0);
out.write(b4, 0, len);
//out.write( Base64.decode4to3( buffer ) );
position = 0;
} // end if: enough to output
} // end if: meaningful base64 character
else if (DECODABET[theByte & 0x7f] != WHITE_SPACE_ENC) {
throw new java.io.IOException("Invalid character in Base64 data.");
} // end else: not white space either
} // end else: decoding
}
// in java/org/jhotdraw/io/Base64.java
Override
public void write(byte[] theBytes, int off, int len) throws java.io.IOException {
// Encoding suspended?
if (suspendEncoding) {
super.out.write(theBytes, off, len);
return;
} // end if: supsended
for (int i = 0; i < len; i++) {
write(theBytes[off + i]);
} // end for: each byte written
}
// in java/org/jhotdraw/io/Base64.java
public void flushBase64() throws java.io.IOException {
if (position > 0) {
if (encode) {
out.write(encode3to4(b4, buffer, position));
position = 0;
} // end if: encoding
else {
throw new java.io.IOException("Base64 input not properly padded.");
} // end else: decoding
} // end if: buffer partially full
}
// in java/org/jhotdraw/io/Base64.java
Override
public void close() throws java.io.IOException {
// 1. Ensure that pending characters are written
flushBase64();
// 2. Actually close the stream
// Base class both flushes and closes.
super.close();
buffer = null;
out = null;
}
// in java/org/jhotdraw/io/Base64.java
public void suspendEncoding() throws java.io.IOException {
flushBase64();
this.suspendEncoding = true;
}
// in java/org/jhotdraw/io/StreamPosTokenizer.java
private int read() throws IOException {
// rlw
int data;
if (unread.size() > 0) {
data = ((Integer) unread.lastElement()).intValue();
unread.removeElementAt(unread.size() - 1);
} else {
data = reader.read();
}
if (data != -1) { readpos++; }
return data;
}
// in java/org/jhotdraw/io/StreamPosTokenizer.java
public int nextChar() throws IOException {
if (pushedBack) {
throw new IllegalStateException("can't read char when a token has been pushed back");
}
if (peekc == NEED_CHAR) {
return read();
} else {
int ch = peekc;
peekc = NEED_CHAR;
return ch;
}
}
// in java/org/jhotdraw/io/StreamPosTokenizer.java
public void pushCharBack(int ch) throws IOException {
if (pushedBack) {
throw new IllegalStateException("can't push back char when a token has been pushed back");
}
if (peekc == NEED_CHAR) {
unread(ch);
} else {
unread(peekc);
peekc = NEED_CHAR;
unread(ch);
}
}
// in java/org/jhotdraw/io/BoundedRangeInputStream.java
Override
public int read()
throws IOException {
int c = in.read();
if (c >=0)
{ incrementValue(1); }
return c;
}
// in java/org/jhotdraw/io/BoundedRangeInputStream.java
Override
public int read(byte b[])
throws IOException {
int nr = in.read(b);
incrementValue(nr);
return nr;
}
// in java/org/jhotdraw/io/BoundedRangeInputStream.java
Override
public int read(byte b[],int off,int len)
throws IOException {
int nr = in.read(b, off, len);
incrementValue(nr);
return nr;
}
// in java/org/jhotdraw/io/BoundedRangeInputStream.java
Override
public long skip(long n) throws IOException {
long nr = in.skip(n);
incrementValue( (int)nr);
return nr;
}
// in java/org/jhotdraw/io/BoundedRangeInputStream.java
Override
public synchronized void reset()
throws IOException {
in.reset();
nread = size-in.available();
fireStateChanged();
}
// in java/org/jhotdraw/app/action/app/ExitAction.java
Override
protected Object construct() throws IOException {
v.write(uri, chooser);
return null;
}
// in java/org/jhotdraw/app/action/app/ExitAction.java
Override
protected Object construct() throws IOException {
v.write(uri, chooser);
return null;
}
// in java/org/jhotdraw/app/action/app/OpenApplicationFileAction.java
protected void openView(final View view, final URI uri) {
final Application app = getApplication();
app.setEnabled(true);
// If there is another view with the same URI we set the multiple open
// id of our view to max(multiple open id) + 1.
int multipleOpenId = 1;
for (View aView : app.views()) {
if (aView != view
&& aView.getURI() != null
&& aView.getURI().equals(uri)) {
multipleOpenId = Math.max(multipleOpenId, aView.getMultipleOpenId() + 1);
}
}
view.setMultipleOpenId(multipleOpenId);
view.setEnabled(false);
// Open the file
view.execute(new Worker() {
@Override
protected Object construct() throws IOException {
boolean exists = true;
try {
File f = new File(uri);
exists = f.exists();
} catch (IllegalArgumentException e) {
// The URI does not denote a file, thus we can not check whether the file exists.
}
if (exists) {
view.read(uri, null);
return null;
} else {
ResourceBundleUtil labels = ResourceBundleUtil.getBundle("org.jhotdraw.app.Labels");
throw new IOException(labels.getFormatted("file.open.fileDoesNotExist.message", URIUtil.getName(uri)));
}
}
@Override
protected void done(Object value) {
view.setURI(uri);
app.addRecentURI(uri);
Frame w = (Frame) SwingUtilities.getWindowAncestor(view.getComponent());
if (w != null) {
w.setExtendedState(w.getExtendedState() & ~Frame.ICONIFIED);
w.toFront();
}
view.setEnabled(true);
view.getComponent().requestFocus();
}
@Override
protected void failed(Throwable value) {
value.printStackTrace();
String message = value.getMessage() != null ? value.getMessage() : value.toString();
ResourceBundleUtil labels = ResourceBundleUtil.getBundle("org.jhotdraw.app.Labels");
JSheet.showMessageSheet(view.getComponent(),
"<html>" + UIManager.getString("OptionPane.css")
+ "<b>" + labels.getFormatted("file.open.couldntOpen.message", URIUtil.getName(uri)) + "</b><p>"
+ (message == null ? "" : message),
JOptionPane.ERROR_MESSAGE, new SheetListener() {
@Override
public void optionSelected(SheetEvent evt) {
view.setEnabled(true);
}
});
}
});
}
// in java/org/jhotdraw/app/action/app/OpenApplicationFileAction.java
Override
protected Object construct() throws IOException {
boolean exists = true;
try {
File f = new File(uri);
exists = f.exists();
} catch (IllegalArgumentException e) {
// The URI does not denote a file, thus we can not check whether the file exists.
}
if (exists) {
view.read(uri, null);
return null;
} else {
ResourceBundleUtil labels = ResourceBundleUtil.getBundle("org.jhotdraw.app.Labels");
throw new IOException(labels.getFormatted("file.open.fileDoesNotExist.message", URIUtil.getName(uri)));
}
}
// in java/org/jhotdraw/app/action/app/PrintApplicationFileAction.java
public void actionPerformed(ActionEvent evt) {
final Application app = getApplication();
final String filename = evt.getActionCommand();
View v = app.createView();
if (!(v instanceof PrintableView)) {
return;
}
final PrintableView p = (PrintableView) v;
p.setEnabled(false);
app.add(p);
// app.show(p);
p.execute(new Worker() {
@Override
public Object construct() throws IOException {
p.read(new File(filename).toURI(), null);
return null;
}
@Override
protected void done(Object value) {
p.setURI(new File(filename).toURI());
p.setEnabled(false);
if (System.getProperty("apple.awt.graphics.UseQuartz", "false").equals("true")) {
printQuartz(p);
} else {
printJava2D(p);
}
p.setEnabled(true);
app.dispose(p);
}
@Override
protected void failed(Throwable value) {
ResourceBundleUtil labels = ResourceBundleUtil.getBundle("org.jhotdraw.app.Labels");
app.dispose(p);
JOptionPane.showMessageDialog(
null,
"<html>" + UIManager.getString("OptionPane.css")
+ "<b>" + labels.getFormatted("file.open.couldntOpen.message", new File(filename).getName()) + "</b><p>"
+ value,
"",
JOptionPane.ERROR_MESSAGE);
}
});
}
// in java/org/jhotdraw/app/action/app/PrintApplicationFileAction.java
Override
public Object construct() throws IOException {
p.read(new File(filename).toURI(), null);
return null;
}
// in java/org/jhotdraw/app/action/AbstractSaveUnsavedChangesAction.java
Override
protected Object construct() throws IOException {
v.write(uri, chooser);
return null;
}
// in java/org/jhotdraw/app/action/file/SaveFileAction.java
Override
protected Object construct() throws IOException {
view.write(file, chooser);
return null;
}
// in java/org/jhotdraw/app/action/file/LoadFileAction.java
public void loadViewFromURI(final View view, final URI uri, final URIChooser chooser) {
view.setEnabled(false);
// Open the file
view.execute(new Worker() {
@Override
protected Object construct() throws IOException {
view.read(uri, chooser);
return null;
}
@Override
protected void done(Object value) {
view.setURI(uri);
view.setEnabled(true);
getApplication().addRecentURI(uri);
}
@Override
protected void failed(Throwable value) {
value.printStackTrace();
ResourceBundleUtil labels = ResourceBundleUtil.getBundle("org.jhotdraw.app.Labels");
JSheet.showMessageSheet(view.getComponent(),
"<html>" + UIManager.getString("OptionPane.css")
+ "<b>" + labels.getFormatted("file.load.couldntLoad.message", URIUtil.getName(uri)) + "</b><p>"
+ ((value == null) ? "" : value),
JOptionPane.ERROR_MESSAGE, new SheetListener() {
@Override
public void optionSelected(SheetEvent evt) {
view.clear();
view.setEnabled(true);
}
});
}
});
}
// in java/org/jhotdraw/app/action/file/LoadFileAction.java
Override
protected Object construct() throws IOException {
view.read(uri, chooser);
return null;
}
// in java/org/jhotdraw/app/action/file/LoadRecentFileAction.java
Override
public void doIt(View v) {
final Application app = getApplication();
// Prevent same URI from being opened more than once
if (!getApplication().getModel().isAllowMultipleViewsPerURI()) {
for (View vw : getApplication().getViews()) {
if (vw.getURI() != null && vw.getURI().equals(uri)) {
vw.getComponent().requestFocus();
return;
}
}
}
// Search for an empty view
if (v == null) {
View emptyView = app.getActiveView();
if (emptyView == null
|| emptyView.getURI() != null
|| emptyView.hasUnsavedChanges()) {
emptyView = null;
}
if (emptyView == null) {
v = app.createView();
app.add(v);
app.show(v);
} else {
v = emptyView;
}
}
final View view = v;
app.setEnabled(true);
view.setEnabled(false);
// If there is another view with the same file we set the multiple open
// id of our view to max(multiple open id) + 1.
int multipleOpenId = 1;
for (View aView : app.views()) {
if (aView != view
&& aView.getURI() != null
&& aView.getURI().equals(uri)) {
multipleOpenId = Math.max(multipleOpenId, aView.getMultipleOpenId() + 1);
}
}
view.setMultipleOpenId(multipleOpenId);
// Open the file
view.execute(new Worker() {
@Override
protected Object construct() throws IOException {
boolean exists = true;
try {
File f = new File(uri);
exists = f.exists();
} catch (IllegalArgumentException e) {
// The URI does not denote a file, thus we can not check whether the file exists.
}
if (exists) {
view.read(uri, null);
return null;
} else {
ResourceBundleUtil labels = ResourceBundleUtil.getBundle("org.jhotdraw.app.Labels");
throw new IOException(labels.getFormatted("file.load.fileDoesNotExist.message", URIUtil.getName(uri)));
}
}
@Override
protected void done(Object value) {
final Application app = getApplication();
view.setURI(uri);
app.addRecentURI(uri);
Frame w = (Frame) SwingUtilities.getWindowAncestor(view.getComponent());
if (w != null) {
w.setExtendedState(w.getExtendedState() & ~Frame.ICONIFIED);
w.toFront();
}
view.getComponent().requestFocus();
app.setEnabled(true);
}
@Override
protected void failed(Throwable error) {
error.printStackTrace();
ResourceBundleUtil labels = ResourceBundleUtil.getBundle("org.jhotdraw.app.Labels");
JSheet.showMessageSheet(view.getComponent(),
"<html>" + UIManager.getString("OptionPane.css")
+ "<b>" + labels.getFormatted("file.load.couldntLoad.message", URIUtil.getName(uri)) + "</b><p>"
+ error,
JOptionPane.ERROR_MESSAGE, new SheetListener() {
@Override
public void optionSelected(SheetEvent evt) {
// app.dispose(view);
}
});
}
@Override
protected void finished() {
view.setEnabled(true);
}
});
}
// in java/org/jhotdraw/app/action/file/LoadRecentFileAction.java
Override
protected Object construct() throws IOException {
boolean exists = true;
try {
File f = new File(uri);
exists = f.exists();
} catch (IllegalArgumentException e) {
// The URI does not denote a file, thus we can not check whether the file exists.
}
if (exists) {
view.read(uri, null);
return null;
} else {
ResourceBundleUtil labels = ResourceBundleUtil.getBundle("org.jhotdraw.app.Labels");
throw new IOException(labels.getFormatted("file.load.fileDoesNotExist.message", URIUtil.getName(uri)));
}
}
// in java/org/jhotdraw/app/action/file/ExportFileAction.java
Override
protected Object construct() throws IOException {
view.write(uri, chooser);
return null;
}
// in java/org/jhotdraw/app/action/file/OpenFileAction.java
protected void openViewFromURI(final View view, final URI uri, final URIChooser chooser) {
final Application app = getApplication();
app.setEnabled(true);
view.setEnabled(false);
// If there is another view with the same URI we set the multiple open
// id of our view to max(multiple open id) + 1.
int multipleOpenId = 1;
for (View aView : app.views()) {
if (aView != view
&& aView.isEmpty()) {
multipleOpenId = Math.max(multipleOpenId, aView.getMultipleOpenId() + 1);
}
}
view.setMultipleOpenId(multipleOpenId);
view.setEnabled(false);
// Open the file
view.execute(new Worker() {
@Override
public Object construct() throws IOException {
boolean exists = true;
try {
exists = new File(uri).exists();
} catch (IllegalArgumentException e) {
}
if (exists) {
view.read(uri, chooser);
return null;
} else {
ResourceBundleUtil labels = ResourceBundleUtil.getBundle("org.jhotdraw.app.Labels");
throw new IOException(labels.getFormatted("file.open.fileDoesNotExist.message", URIUtil.getName(uri)));
}
}
@Override
protected void done(Object value) {
final Application app = getApplication();
view.setURI(uri);
view.setEnabled(true);
Frame w = (Frame) SwingUtilities.getWindowAncestor(view.getComponent());
if (w != null) {
w.setExtendedState(w.getExtendedState() & ~Frame.ICONIFIED);
w.toFront();
}
view.getComponent().requestFocus();
app.addRecentURI(uri);
app.setEnabled(true);
}
@Override
protected void failed(Throwable value) {
value.printStackTrace();
view.setEnabled(true);
app.setEnabled(true);
String message = value.getMessage() != null ? value.getMessage() : value.toString();
ResourceBundleUtil labels = ResourceBundleUtil.getBundle("org.jhotdraw.app.Labels");
JSheet.showMessageSheet(view.getComponent(),
"<html>" + UIManager.getString("OptionPane.css")
+ "<b>" + labels.getFormatted("file.open.couldntOpen.message", URIUtil.getName(uri)) + "</b><p>"
+ ((message == null) ? "" : message),
JOptionPane.ERROR_MESSAGE);
}
});
}
// in java/org/jhotdraw/app/action/file/OpenFileAction.java
Override
public Object construct() throws IOException {
boolean exists = true;
try {
exists = new File(uri).exists();
} catch (IllegalArgumentException e) {
}
if (exists) {
view.read(uri, chooser);
return null;
} else {
ResourceBundleUtil labels = ResourceBundleUtil.getBundle("org.jhotdraw.app.Labels");
throw new IOException(labels.getFormatted("file.open.fileDoesNotExist.message", URIUtil.getName(uri)));
}
}
// in java/org/jhotdraw/app/action/file/OpenRecentFileAction.java
protected void openView(final View view) {
final Application app = getApplication();
app.setEnabled(true);
// If there is another view with the same URI we set the multiple open
// id of our view to max(multiple open id) + 1.
int multipleOpenId = 1;
for (View aView : app.views()) {
if (aView != view
&& aView.isEmpty()) {
multipleOpenId = Math.max(multipleOpenId, aView.getMultipleOpenId() + 1);
}
}
view.setMultipleOpenId(multipleOpenId);
view.setEnabled(false);
// Open the file
view.execute(new Worker() {
@Override
protected Object construct() throws IOException {
boolean exists = true;
try {
File f = new File(uri);
exists = f.exists();
} catch (IllegalArgumentException e) {
// The URI does not denote a file, thus we can not check whether the file exists.
}
if (exists) {
view.read(uri, null);
return null;
} else {
ResourceBundleUtil labels = ResourceBundleUtil.getBundle("org.jhotdraw.app.Labels");
throw new IOException(labels.getFormatted("file.open.fileDoesNotExist.message", URIUtil.getName(uri)));
}
}
@Override
protected void done(Object value) {
view.setURI(uri);
Frame w = (Frame) SwingUtilities.getWindowAncestor(view.getComponent());
if (w != null) {
w.setExtendedState(w.getExtendedState() & ~Frame.ICONIFIED);
w.toFront();
}
app.addRecentURI(uri);
view.setEnabled(true);
view.getComponent().requestFocus();
}
@Override
protected void failed(Throwable value) {
value.printStackTrace();
String message = value.getMessage() != null ? value.getMessage() : value.toString();
ResourceBundleUtil labels = ResourceBundleUtil.getBundle("org.jhotdraw.app.Labels");
JSheet.showMessageSheet(view.getComponent(),
"<html>" + UIManager.getString("OptionPane.css")
+ "<b>" + labels.getFormatted("file.open.couldntOpen.message", URIUtil.getName(uri)) + "</b><p>"
+ (message == null ? "" : message),
JOptionPane.ERROR_MESSAGE, new SheetListener() {
@Override
public void optionSelected(SheetEvent evt) {
view.setEnabled(true);
}
});
}
});
}
// in java/org/jhotdraw/app/action/file/OpenRecentFileAction.java
Override
protected Object construct() throws IOException {
boolean exists = true;
try {
File f = new File(uri);
exists = f.exists();
} catch (IllegalArgumentException e) {
// The URI does not denote a file, thus we can not check whether the file exists.
}
if (exists) {
view.read(uri, null);
return null;
} else {
ResourceBundleUtil labels = ResourceBundleUtil.getBundle("org.jhotdraw.app.Labels");
throw new IOException(labels.getFormatted("file.open.fileDoesNotExist.message", URIUtil.getName(uri)));
}
}
// in java/org/jhotdraw/draw/AbstractAttributedDecoratedFigure.java
Override
public void read(DOMInput in) throws IOException {
super.read(in);
readDecorator(in);
}
// in java/org/jhotdraw/draw/AbstractAttributedDecoratedFigure.java
Override
public void write(DOMOutput out) throws IOException {
super.write(out);
writeDecorator(out);
}
// in java/org/jhotdraw/draw/AbstractAttributedDecoratedFigure.java
protected void writeDecorator(DOMOutput out) throws IOException {
if (decorator != null) {
out.openElement("decorator");
out.writeObject(decorator);
out.closeElement();
}
}
// in java/org/jhotdraw/draw/AbstractAttributedDecoratedFigure.java
protected void readDecorator(DOMInput in) throws IOException {
if (in.getElementCount("decorator") > 0) {
in.openElement("decorator");
decorator = (Figure) in.readObject();
in.closeElement();
} else {
decorator = null;
}
}
// in java/org/jhotdraw/draw/RoundRectangleFigure.java
Override
public void read(DOMInput in) throws IOException {
super.read(in);
roundrect.arcwidth = in.getAttribute("arcWidth", DEFAULT_ARC);
roundrect.archeight = in.getAttribute("arcHeight", DEFAULT_ARC);
}
// in java/org/jhotdraw/draw/RoundRectangleFigure.java
Override
public void write(DOMOutput out) throws IOException {
super.write(out);
out.addAttribute("arcWidth", roundrect.arcwidth);
out.addAttribute("arcHeight", roundrect.archeight);
}
// in java/org/jhotdraw/draw/decoration/CompositeLineDecoration.java
Override
public void read(DOMInput in) throws IOException {
for (int i = in.getElementCount("decoration") - 1; i >= 0; i--) {
in.openElement("decoration", i);
Object value = in.readObject();
if (value instanceof LineDecoration)
addDecoration((LineDecoration)value);
in.closeElement();
}
}
// in java/org/jhotdraw/draw/decoration/CompositeLineDecoration.java
Override
public void write(DOMOutput out) throws IOException {
for (LineDecoration decoration : decorations) {
out.openElement("decoration");
out.writeObject(decoration);
out.closeElement();
}
}
// in java/org/jhotdraw/draw/LineConnectionFigure.java
Override
protected void readPoints(DOMInput in) throws IOException {
super.readPoints(in);
in.openElement("startConnector");
setStartConnector((Connector) in.readObject());
in.closeElement();
in.openElement("endConnector");
setEndConnector((Connector) in.readObject());
in.closeElement();
}
// in java/org/jhotdraw/draw/LineConnectionFigure.java
Override
public void read(DOMInput in) throws IOException {
readAttributes(in);
readLiner(in);
// Note: Points must be read after Liner, because Liner influences
// the location of the points.
readPoints(in);
}
// in java/org/jhotdraw/draw/LineConnectionFigure.java
protected void readLiner(DOMInput in) throws IOException {
if (in.getElementCount("liner") > 0) {
in.openElement("liner");
liner = (Liner) in.readObject();
in.closeElement();
} else {
liner = null;
}
}
// in java/org/jhotdraw/draw/LineConnectionFigure.java
Override
public void write(DOMOutput out) throws IOException {
writePoints(out);
writeAttributes(out);
writeLiner(out);
}
// in java/org/jhotdraw/draw/LineConnectionFigure.java
protected void writeLiner(DOMOutput out) throws IOException {
if (liner != null) {
out.openElement("liner");
out.writeObject(liner);
out.closeElement();
}
}
// in java/org/jhotdraw/draw/LineConnectionFigure.java
Override
protected void writePoints(DOMOutput out) throws IOException {
super.writePoints(out);
out.openElement("startConnector");
out.writeObject(getStartConnector());
out.closeElement();
out.openElement("endConnector");
out.writeObject(getEndConnector());
out.closeElement();
}
// in java/org/jhotdraw/draw/io/ImageOutputFormat.java
Override
public void write(URI uri, Drawing drawing) throws IOException {
write(new File(uri),drawing);
}
// in java/org/jhotdraw/draw/io/ImageOutputFormat.java
public void write(File file, Drawing drawing) throws IOException {
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
try {
write(out, drawing);
} finally {
out.close();
}
}
// in java/org/jhotdraw/draw/io/ImageOutputFormat.java
Override
public void write(OutputStream out, Drawing drawing) throws IOException {
write(out, drawing, drawing.getChildren(), null, null);
}
// in java/org/jhotdraw/draw/io/ImageOutputFormat.java
public void write(OutputStream out, Drawing drawing,
AffineTransform drawingTransform, Dimension imageSize) throws IOException {
write(out, drawing, drawing.getChildren(), drawingTransform, imageSize);
}
// in java/org/jhotdraw/draw/io/ImageOutputFormat.java
Override
public Transferable createTransferable(Drawing drawing, java.util.List<Figure> figures, double scaleFactor) throws IOException {
return new ImageTransferable(toImage(drawing, figures, scaleFactor, true));
}
// in java/org/jhotdraw/draw/io/ImageOutputFormat.java
public void write(OutputStream out, Drawing drawing, java.util.List<Figure> figures) throws IOException {
write(out, drawing, figures, null, null);
}
// in java/org/jhotdraw/draw/io/DOMStorableInputOutputFormat.java
protected void read(URL url, InputStream in, Drawing drawing, LinkedList<Figure> figures) throws IOException {
NanoXMLDOMInput domi = new NanoXMLDOMInput(factory, in);
domi.openElement(factory.getName(drawing));
domi.openElement("figures", 0);
figures.clear();
for (int i = 0, n = domi.getElementCount(); i < n; i++) {
Figure f = (Figure) domi.readObject();
figures.add(f);
}
domi.closeElement();
domi.closeElement();
drawing.basicAddAll(drawing.getChildCount(), figures);
}
// in java/org/jhotdraw/draw/io/DOMStorableInputOutputFormat.java
Override
public void write(URI uri, Drawing drawing) throws IOException {
write(new File(uri),drawing);
}
// in java/org/jhotdraw/draw/io/DOMStorableInputOutputFormat.java
public void write(File file, Drawing drawing) throws IOException {
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
try {
write(out, drawing);
} finally {
out.close();
}
}
// in java/org/jhotdraw/draw/io/DOMStorableInputOutputFormat.java
Override
public void write(OutputStream out, Drawing drawing) throws IOException {
NanoXMLDOMOutput domo = new NanoXMLDOMOutput(factory);
domo.openElement(factory.getName(drawing));
drawing.write(domo);
domo.closeElement();
domo.save(out);
domo.dispose();
}
// in java/org/jhotdraw/draw/io/DOMStorableInputOutputFormat.java
Override
public void read(URI uri, Drawing drawing) throws IOException {
read(new File(uri), drawing);
}
// in java/org/jhotdraw/draw/io/DOMStorableInputOutputFormat.java
Override
public void read(URI uri, Drawing drawing, boolean replace) throws IOException {
read(new File(uri), drawing, replace);
}
// in java/org/jhotdraw/draw/io/DOMStorableInputOutputFormat.java
public void read(File file, Drawing drawing) throws IOException {
read(file, drawing, true);
}
// in java/org/jhotdraw/draw/io/DOMStorableInputOutputFormat.java
public void read(File file, Drawing drawing, boolean replace) throws IOException {
BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
try {
read(in, drawing, replace);
} finally {
in.close();
}
}
// in java/org/jhotdraw/draw/io/DOMStorableInputOutputFormat.java
Override
public void read(InputStream in, Drawing drawing, boolean replace) throws IOException {
NanoXMLDOMInput domi = new NanoXMLDOMInput(factory, in);
domi.openElement(factory.getName(drawing));
if (replace) {
drawing.removeAllChildren();
}
drawing.read(domi);
domi.closeElement();
domi.dispose();
}
// in java/org/jhotdraw/draw/io/DOMStorableInputOutputFormat.java
Override
public void read(Transferable t, Drawing drawing, boolean replace) throws UnsupportedFlavorException, IOException {
LinkedList<Figure> figures = new LinkedList<Figure>();
InputStream in = (InputStream) t.getTransferData(new DataFlavor(mimeType, description));
NanoXMLDOMInput domi = new NanoXMLDOMInput(factory, in);
domi.openElement("Drawing-Clip");
for (int i = 0, n = domi.getElementCount(); i < n; i++) {
Figure f = (Figure) domi.readObject(i);
figures.add(f);
}
domi.closeElement();
if (replace) {
drawing.removeAllChildren();
}
drawing.addAll(figures);
}
// in java/org/jhotdraw/draw/io/DOMStorableInputOutputFormat.java
Override
public Transferable createTransferable(Drawing drawing, List<Figure> figures, double scaleFactor) throws IOException {
ByteArrayOutputStream buf = new ByteArrayOutputStream();
NanoXMLDOMOutput domo = new NanoXMLDOMOutput(factory);
domo.openElement("Drawing-Clip");
for (Figure f : figures) {
domo.writeObject(f);
}
domo.closeElement();
domo.save(buf);
return new InputStreamTransferable(new DataFlavor(mimeType, description), buf.toByteArray());
}
// in java/org/jhotdraw/draw/io/SerializationInputOutputFormat.java
Override
public void read(URI uri, Drawing drawing) throws IOException {
read(new File(uri), drawing);
}
// in java/org/jhotdraw/draw/io/SerializationInputOutputFormat.java
Override
public void read(URI uri, Drawing drawing, boolean replace) throws IOException {
read(new File(uri), drawing, replace);
}
// in java/org/jhotdraw/draw/io/SerializationInputOutputFormat.java
public void read(File file, Drawing drawing) throws IOException {
read(file, drawing, true);
}
// in java/org/jhotdraw/draw/io/SerializationInputOutputFormat.java
public void read(File file, Drawing drawing, boolean replace) throws IOException {
BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
try {
read(in, drawing, replace);
} finally {
in.close();
}
}
// in java/org/jhotdraw/draw/io/SerializationInputOutputFormat.java
Override
public void write(URI uri, Drawing drawing) throws IOException {
write(new File(uri),drawing);
}
// in java/org/jhotdraw/draw/io/SerializationInputOutputFormat.java
public void write(File file, Drawing drawing) throws IOException {
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
try {
write(out, drawing);
} finally {
out.close();
}
}
// in java/org/jhotdraw/draw/io/SerializationInputOutputFormat.java
Override
public void write(OutputStream out, Drawing drawing) throws IOException {
ObjectOutputStream oout = new ObjectOutputStream(out);
oout.writeObject(drawing);
oout.flush();
}
// in java/org/jhotdraw/draw/io/SerializationInputOutputFormat.java
Override
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
if (isDataFlavorSupported(flavor)) {
return d;
} else {
throw new UnsupportedFlavorException(flavor);
}
}
// in java/org/jhotdraw/draw/io/TextInputFormat.java
Override
public void read(URI uri, Drawing drawing) throws IOException {
read(new File(uri), drawing);
}
// in java/org/jhotdraw/draw/io/TextInputFormat.java
Override
public void read(URI uri, Drawing drawing, boolean replace) throws IOException {
read(new File(uri), drawing, replace);
}
// in java/org/jhotdraw/draw/io/TextInputFormat.java
public void read(File file, Drawing drawing) throws IOException {
read(file, drawing, true);
}
// in java/org/jhotdraw/draw/io/TextInputFormat.java
public void read(File file, Drawing drawing, boolean replace) throws IOException {
InputStream in = new FileInputStream(file);
try {
read(in, drawing, replace);
} finally {
in.close();
}
}
// in java/org/jhotdraw/draw/io/TextInputFormat.java
Override
public void read(InputStream in, Drawing drawing, boolean replace) throws IOException {
if (replace) {
drawing.removeAllChildren();
}
drawing.basicAddAll(0, createTextHolderFigures(in));
}
// in java/org/jhotdraw/draw/io/TextInputFormat.java
public LinkedList<Figure> createTextHolderFigures(InputStream in) throws IOException {
LinkedList<Figure> list = new LinkedList<Figure>();
BufferedReader r = new BufferedReader(new InputStreamReader(in, "UTF8"));
if (isMultiline) {
TextHolderFigure figure = (TextHolderFigure) prototype.clone();
StringBuilder buf = new StringBuilder();
for (String line = null; line != null; line = r.readLine()) {
if (buf.length() != 0) {
buf.append('\n');
}
buf.append(line);
}
figure.setText(buf.toString());
Dimension2DDouble s = figure.getPreferredSize();
figure.setBounds(
new Point2D.Double(0, 0),
new Point2D.Double(
s.width, s.height));
} else {
double y = 0;
for (String line = null; line != null; line = r.readLine()) {
TextHolderFigure figure = (TextHolderFigure) prototype.clone();
figure.setText(line);
Dimension2DDouble s = figure.getPreferredSize();
figure.setBounds(
new Point2D.Double(0, y),
new Point2D.Double(
s.width, s.height));
list.add(figure);
y += s.height;
}
}
if (list.size() == 0) {
throw new IOException("No text found");
}
return list;
}
// in java/org/jhotdraw/draw/io/TextInputFormat.java
Override
public void read(Transferable t, Drawing drawing, boolean replace) throws UnsupportedFlavorException, IOException {
String text = (String) t.getTransferData(DataFlavor.stringFlavor);
LinkedList<Figure> list = new LinkedList<Figure>();
if (isMultiline) {
TextHolderFigure figure = (TextHolderFigure) prototype.clone();
figure.setText(text);
Dimension2DDouble s = figure.getPreferredSize();
figure.willChange();
figure.setBounds(
new Point2D.Double(0, 0),
new Point2D.Double(
s.width, s.height));
figure.changed();
list.add(figure);
} else {
double y = 0;
for (String line : text.split("\n")) {
TextHolderFigure figure = (TextHolderFigure) prototype.clone();
figure.setText(line);
Dimension2DDouble s = figure.getPreferredSize();
y += s.height;
figure.willChange();
figure.setBounds(
new Point2D.Double(0, 0 + y),
new Point2D.Double(
s.width, s.height + y));
figure.changed();
list.add(figure);
}
}
if (replace) {
drawing.removeAllChildren();
}
drawing.addAll(list);
}
// in java/org/jhotdraw/draw/io/ImageInputFormat.java
Override
public void read(URI uri, Drawing drawing) throws IOException {
read(new File(uri), drawing);
}
// in java/org/jhotdraw/draw/io/ImageInputFormat.java
Override
public void read(URI uri, Drawing drawing, boolean replace) throws IOException {
read(new File(uri), drawing, replace);
}
// in java/org/jhotdraw/draw/io/ImageInputFormat.java
public void read(File file, Drawing drawing, boolean replace) throws IOException {
ImageHolderFigure figure = (ImageHolderFigure) prototype.clone();
figure.loadImage(file);
figure.setBounds(
new Point2D.Double(0, 0),
new Point2D.Double(
figure.getBufferedImage().getWidth(),
figure.getBufferedImage().getHeight()));
if (replace) {
drawing.removeAllChildren();
drawing.set(CANVAS_WIDTH, figure.getBounds().width);
drawing.set(CANVAS_HEIGHT, figure.getBounds().height);
}
drawing.basicAdd(figure);
}
// in java/org/jhotdraw/draw/io/ImageInputFormat.java
public void read(File file, Drawing drawing) throws IOException {
read(file, drawing, true);
}
// in java/org/jhotdraw/draw/io/ImageInputFormat.java
Override
public void read(InputStream in, Drawing drawing, boolean replace) throws IOException {
ImageHolderFigure figure = createImageHolder(in);
if (replace) {
drawing.removeAllChildren();
drawing.set(CANVAS_WIDTH, figure.getBounds().width);
drawing.set(CANVAS_HEIGHT, figure.getBounds().height);
}
drawing.basicAdd(figure);
}
// in java/org/jhotdraw/draw/io/ImageInputFormat.java
public ImageHolderFigure createImageHolder(InputStream in) throws IOException {
ImageHolderFigure figure = (ImageHolderFigure) prototype.clone();
figure.loadImage(in);
figure.setBounds(
new Point2D.Double(0, 0),
new Point2D.Double(
figure.getBufferedImage().getWidth(),
figure.getBufferedImage().getHeight()));
return figure;
}
// in java/org/jhotdraw/draw/io/ImageInputFormat.java
Override
public void read(Transferable t, Drawing drawing, boolean replace) throws UnsupportedFlavorException, IOException {
DataFlavor importFlavor = null;
SearchLoop:
for (DataFlavor flavor : t.getTransferDataFlavors()) {
if (DataFlavor.imageFlavor.match(flavor)) {
importFlavor = flavor;
break SearchLoop;
}
for (String mimeType : mimeTypes) {
if (flavor.isMimeTypeEqual(mimeType)) {
importFlavor = flavor;
break SearchLoop;
}
}
}
Object data = t.getTransferData(importFlavor);
Image img = null;
if (data instanceof Image) {
img = (Image) data;
} else if (data instanceof InputStream) {
img = ImageIO.read((InputStream) data);
}
if (img == null) {
throw new IOException("Unsupported data format " + importFlavor);
}
ImageHolderFigure figure = (ImageHolderFigure) prototype.clone();
figure.setBufferedImage(Images.toBufferedImage(img));
figure.setBounds(
new Point2D.Double(0, 0),
new Point2D.Double(
figure.getBufferedImage().getWidth(),
figure.getBufferedImage().getHeight()));
LinkedList<Figure> list = new LinkedList<Figure>();
list.add(figure);
if (replace) {
drawing.removeAllChildren();
drawing.set(CANVAS_WIDTH, figure.getBounds().width);
drawing.set(CANVAS_HEIGHT, figure.getBounds().height);
}
drawing.addAll(list);
}
// in java/org/jhotdraw/draw/AbstractCompositeFigure.java
Override
public void read(DOMInput in) throws IOException {
in.openElement("children");
for (int i = 0; i < in.getElementCount(); i++) {
basicAdd((Figure) in.readObject(i));
}
in.closeElement();
}
// in java/org/jhotdraw/draw/AbstractCompositeFigure.java
Override
public void write(DOMOutput out) throws IOException {
out.openElement("children");
for (Figure child : getChildren()) {
out.writeObject(child);
}
out.closeElement();
}
// in java/org/jhotdraw/draw/TextFigure.java
Override
public void read(DOMInput in) throws IOException {
setBounds(
new Point2D.Double(in.getAttribute("x", 0d), in.getAttribute("y", 0d)),
new Point2D.Double(0, 0));
readAttributes(in);
readDecorator(in);
invalidate();
}
// in java/org/jhotdraw/draw/TextFigure.java
Override
public void write(DOMOutput out) throws IOException {
Rectangle2D.Double b = getBounds();
out.addAttribute("x", b.x);
out.addAttribute("y", b.y);
writeAttributes(out);
writeDecorator(out);
}
// in java/org/jhotdraw/draw/AbstractAttributedFigure.java
protected void writeAttributes(DOMOutput out) throws IOException {
Figure prototype = (Figure) out.getPrototype();
boolean isElementOpen = false;
for (Map.Entry<AttributeKey, Object> entry : attributes.entrySet()) {
AttributeKey key = entry.getKey();
if (forbiddenAttributes == null
|| ! forbiddenAttributes.contains(key)) {
@SuppressWarnings("unchecked")
Object prototypeValue = prototype.get(key);
@SuppressWarnings("unchecked")
Object attributeValue = get(key);
if (prototypeValue != attributeValue ||
(prototypeValue != null && attributeValue != null &&
! prototypeValue.equals(attributeValue))) {
if (! isElementOpen) {
out.openElement("a");
isElementOpen = true;
}
out.openElement(key.getKey());
out.writeObject(entry.getValue());
out.closeElement();
}
}
}
if (isElementOpen) {
out.closeElement();
}
}
// in java/org/jhotdraw/draw/AbstractAttributedFigure.java
Override
public void write(DOMOutput out) throws IOException {
Rectangle2D.Double r = getBounds();
out.addAttribute("x", r.x);
out.addAttribute("y", r.y);
out.addAttribute("w", r.width);
out.addAttribute("h", r.height);
writeAttributes(out);
}
// in java/org/jhotdraw/draw/AbstractAttributedFigure.java
Override
public void read(DOMInput in) throws IOException {
double x = in.getAttribute("x", 0d);
double y = in.getAttribute("y", 0d);
double w = in.getAttribute("w", 0d);
double h = in.getAttribute("h", 0d);
setBounds(new Point2D.Double(x,y), new Point2D.Double(x+w,y+h));
readAttributes(in);
}
// in java/org/jhotdraw/draw/AbstractAttributedCompositeFigure.java
protected void writeAttributes(DOMOutput out) throws IOException {
Figure prototype = (Figure) out.getPrototype();
boolean isElementOpen = false;
for (Map.Entry<AttributeKey, Object> entry : attributes.entrySet()) {
AttributeKey key = entry.getKey();
if (forbiddenAttributes == null || !forbiddenAttributes.contains(key)) {
@SuppressWarnings("unchecked")
Object prototypeValue = prototype.get(key);
@SuppressWarnings("unchecked")
Object attributeValue = get(key);
if (prototypeValue != attributeValue ||
(prototypeValue != null && attributeValue != null &&
!prototypeValue.equals(attributeValue))) {
if (!isElementOpen) {
out.openElement("a");
isElementOpen = true;
}
out.openElement(key.getKey());
out.writeObject(entry.getValue());
out.closeElement();
}
}
}
if (isElementOpen) {
out.closeElement();
}
}
// in java/org/jhotdraw/draw/AbstractAttributedCompositeFigure.java
Override
public void write(DOMOutput out) throws IOException {
super.write(out);
writeAttributes(out);
}
// in java/org/jhotdraw/draw/AbstractAttributedCompositeFigure.java
Override
public void read(DOMInput in) throws IOException {
super.read(in);
readAttributes(in);
}
// in java/org/jhotdraw/draw/BezierFigure.java
Override
public void write(DOMOutput out) throws IOException {
writePoints(out);
writeAttributes(out);
}
// in java/org/jhotdraw/draw/BezierFigure.java
protected void writePoints(DOMOutput out) throws IOException {
out.openElement("points");
if (isClosed()) {
out.addAttribute("closed", true);
}
for (int i = 0, n = getNodeCount(); i < n; i++) {
BezierPath.Node node = getNode(i);
out.openElement("p");
out.addAttribute("mask", node.mask, 0);
out.addAttribute("colinear", true);
out.addAttribute("x", node.x[0]);
out.addAttribute("y", node.y[0]);
out.addAttribute("c1x", node.x[1], node.x[0]);
out.addAttribute("c1y", node.y[1], node.y[0]);
out.addAttribute("c2x", node.x[2], node.x[0]);
out.addAttribute("c2y", node.y[2], node.y[0]);
out.closeElement();
}
out.closeElement();
}
// in java/org/jhotdraw/draw/BezierFigure.java
Override
public void read(DOMInput in) throws IOException {
readPoints(in);
readAttributes(in);
}
// in java/org/jhotdraw/draw/BezierFigure.java
protected void readPoints(DOMInput in) throws IOException {
path.clear();
in.openElement("points");
setClosed(in.getAttribute("closed", false));
for (int i = 0, n = in.getElementCount("p"); i < n; i++) {
in.openElement("p", i);
BezierPath.Node node = new BezierPath.Node(
in.getAttribute("mask", 0),
in.getAttribute("x", 0d),
in.getAttribute("y", 0d),
in.getAttribute("c1x", in.getAttribute("x", 0d)),
in.getAttribute("c1y", in.getAttribute("y", 0d)),
in.getAttribute("c2x", in.getAttribute("x", 0d)),
in.getAttribute("c2y", in.getAttribute("y", 0d)));
node.keepColinear = in.getAttribute("colinear", true);
path.add(node);
path.invalidatePath();
in.closeElement();
}
in.closeElement();
}
// in java/org/jhotdraw/draw/ImageFigure.java
Override
public void read(DOMInput in) throws IOException {
super.read(in);
if (in.getElementCount("imageData") > 0) {
in.openElement("imageData");
String base64Data = in.getText();
if (base64Data != null) {
setImageData(Base64.decode(base64Data));
}
in.closeElement();
}
}
// in java/org/jhotdraw/draw/ImageFigure.java
Override
public void write(DOMOutput out) throws IOException {
super.write(out);
if (getImageData() != null) {
out.openElement("imageData");
out.addText(Base64.encodeBytes(getImageData()));
out.closeElement();
}
}
// in java/org/jhotdraw/draw/ImageFigure.java
Override
public void loadImage(File file) throws IOException {
InputStream in = new FileInputStream(file);
try {
loadImage(in);
} catch (Throwable t) {
ResourceBundleUtil labels = ResourceBundleUtil.getBundle("org.jhotdraw.draw.Labels");
IOException e = new IOException(labels.getFormatted("file.failedToLoadImage.message", file.getName()));
e.initCause(t);
throw e;
} finally {
in.close();
}
}
// in java/org/jhotdraw/draw/ImageFigure.java
Override
public void loadImage(InputStream in) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[512];
int bytesRead;
while ((bytesRead = in.read(buf)) > 0) {
baos.write(buf, 0, bytesRead);
}
BufferedImage img = ImageIO.read(new ByteArrayInputStream(baos.toByteArray()));
if (img == null) {
ResourceBundleUtil labels = ResourceBundleUtil.getBundle("org.jhotdraw.draw.Labels");
throw new IOException(labels.getFormatted("file.failedToLoadImage.message", in.toString()));
}
imageData = baos.toByteArray();
bufferedImage = img;
}
// in java/org/jhotdraw/draw/ImageFigure.java
private void writeObject(ObjectOutputStream out) throws IOException {
// The call to getImageData() ensures that we have serializable data
// in the imageData array.
getImageData();
out.defaultWriteObject();
}
// in java/org/jhotdraw/draw/GraphicalCompositeFigure.java
protected void writeAttributes(DOMOutput out) throws IOException {
Figure prototype = (Figure) out.getPrototype();
boolean isElementOpen = false;
for (Map.Entry<AttributeKey, Object> entry : attributes.entrySet()) {
AttributeKey key = entry.getKey();
if (forbiddenAttributes == null
|| !forbiddenAttributes.contains(key)) {
@SuppressWarnings("unchecked")
Object prototypeValue = prototype.get(key);
@SuppressWarnings("unchecked")
Object attributeValue = get(key);
if (prototypeValue != attributeValue
|| (prototypeValue != null && attributeValue != null
&& !prototypeValue.equals(attributeValue))) {
if (!isElementOpen) {
out.openElement("a");
isElementOpen = true;
}
out.openElement(key.getKey());
out.writeObject(entry.getValue());
out.closeElement();
}
}
}
if (isElementOpen) {
out.closeElement();
}
}
// in java/org/jhotdraw/draw/GraphicalCompositeFigure.java
Override
public void read(DOMInput in) throws IOException {
super.read(in);
readAttributes(in);
}
// in java/org/jhotdraw/draw/GraphicalCompositeFigure.java
Override
public void write(DOMOutput out) throws IOException {
super.write(out);
writeAttributes(out);
}
// in java/org/jhotdraw/draw/connector/LocatorConnector.java
Override public void read(DOMInput in) throws IOException {
super.read(in);
in.openElement("locator");
this.locator = (Locator) in.readObject(0);
in.closeElement();
}
// in java/org/jhotdraw/draw/connector/LocatorConnector.java
Override public void write(DOMOutput out) throws IOException {
super.write(out);
out.openElement("locator");
out.writeObject(locator);
out.closeElement();
}
// in java/org/jhotdraw/draw/connector/AbstractConnector.java
Override
public void read(DOMInput in) throws IOException {
if (isStatePersistent) {
isConnectToDecorator = in.getAttribute("connectToDecorator", false);
}
if (in.getElementCount("Owner") != 0) {
in.openElement("Owner");
} else {
in.openElement("owner");
}
this.owner = (Figure) in.readObject(0);
in.closeElement();
}
// in java/org/jhotdraw/draw/connector/AbstractConnector.java
Override
public void write(DOMOutput out) throws IOException {
if (isStatePersistent) {
if (isConnectToDecorator) {
out.addAttribute("connectToDecorator", true);
}
}
out.openElement("Owner");
out.writeObject(getOwner());
out.closeElement();
}
// in java/org/jhotdraw/draw/connector/StickyRectangleConnector.java
Override
public void read(DOMInput in) throws IOException {
super.read(in);
angle = (float) in.getAttribute("angle", 0.0);
}
// in java/org/jhotdraw/draw/connector/StickyRectangleConnector.java
Override
public void write(DOMOutput out) throws IOException {
super.write(out);
out.addAttribute("angle", angle);
}
// in java/org/jhotdraw/draw/TextAreaFigure.java
protected void readBounds(DOMInput in) throws IOException {
bounds.x = in.getAttribute("x", 0d);
bounds.y = in.getAttribute("y", 0d);
bounds.width = in.getAttribute("w", 0d);
bounds.height = in.getAttribute("h", 0d);
}
// in java/org/jhotdraw/draw/TextAreaFigure.java
protected void writeBounds(DOMOutput out) throws IOException {
out.addAttribute("x", bounds.x);
out.addAttribute("y", bounds.y);
out.addAttribute("w", bounds.width);
out.addAttribute("h", bounds.height);
}
// in java/org/jhotdraw/draw/TextAreaFigure.java
Override
public void read(DOMInput in) throws IOException {
readBounds(in);
readAttributes(in);
}
// in java/org/jhotdraw/draw/TextAreaFigure.java
Override
public void write(DOMOutput out) throws IOException {
writeBounds(out);
writeAttributes(out);
}
// in java/org/jhotdraw/draw/tool/ImageTool.java
Override
public void activate(DrawingEditor editor) {
super.activate(editor);
final DrawingView v=getView();
if (v==null)return;
if (workerThread != null) {
try {
workerThread.join();
} catch (InterruptedException ex) {
// ignore
}
}
final File file;
if (useFileDialog) {
getFileDialog().setVisible(true);
if (getFileDialog().getFile() != null) {
file = new File(getFileDialog().getDirectory(), getFileDialog().getFile());
} else {
file = null;
}
} else {
if (getFileChooser().showOpenDialog(v.getComponent()) == JFileChooser.APPROVE_OPTION) {
file = getFileChooser().getSelectedFile();
} else {
file = null;
}
}
if (file != null) {
final ImageHolderFigure loaderFigure = ((ImageHolderFigure) prototype.clone());
Worker worker = new Worker() {
@Override
protected Object construct() throws IOException {
((ImageHolderFigure) loaderFigure).loadImage(file);
return null;
}
@Override
protected void done(Object value) {
try {
if (createdFigure == null) {
((ImageHolderFigure) prototype).setImage(loaderFigure.getImageData(), loaderFigure.getBufferedImage());
} else {
((ImageHolderFigure) createdFigure).setImage(loaderFigure.getImageData(), loaderFigure.getBufferedImage());
}
} catch (IOException ex) {
JOptionPane.showMessageDialog(v.getComponent(),
ex.getMessage(),
null,
JOptionPane.ERROR_MESSAGE);
}
}
@Override
protected void failed(Throwable value) {
Throwable t = (Throwable) value;
JOptionPane.showMessageDialog(v.getComponent(),
t.getMessage(),
null,
JOptionPane.ERROR_MESSAGE);
getDrawing().remove(createdFigure);
fireToolDone();
}
};
workerThread = new Thread(worker);
workerThread.start();
} else {
//getDrawing().remove(createdFigure);
if (isToolDoneAfterCreation()) {
fireToolDone();
}
}
}
// in java/org/jhotdraw/draw/tool/ImageTool.java
Override
protected Object construct() throws IOException {
((ImageHolderFigure) loaderFigure).loadImage(file);
return null;
}
// in java/org/jhotdraw/draw/AbstractDrawing.java
Override
public void read(DOMInput in) throws IOException {
in.openElement("figures");
for (int i = 0; i < in.getElementCount(); i++) {
Figure f;
add(f = (Figure) in.readObject(i));
}
in.closeElement();
}
// in java/org/jhotdraw/draw/AbstractDrawing.java
Override
public void write(DOMOutput out) throws IOException {
out.openElement("figures");
for (Figure f : getChildren()) {
out.writeObject(f);
}
out.closeElement();
}
// in java/org/jhotdraw/samples/pert/PertView.java
Override
public void write(URI f, URIChooser chooser) throws IOException {
Drawing drawing = view.getDrawing();
OutputFormat outputFormat = drawing.getOutputFormats().get(0);
outputFormat.write(f, drawing);
}
// in java/org/jhotdraw/samples/pert/PertView.java
Override
public void read(URI f, URIChooser chooser) throws IOException {
try {
final Drawing drawing = createDrawing();
InputFormat inputFormat = drawing.getInputFormats().get(0);
inputFormat.read(f, drawing, true);
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
view.getDrawing().removeUndoableEditListener(undo);
view.setDrawing(drawing);
view.getDrawing().addUndoableEditListener(undo);
undo.discardAllEdits();
}
});
} catch (InterruptedException e) {
InternalError error = new InternalError();
e.initCause(e);
throw error;
} catch (InvocationTargetException e) {
InternalError error = new InternalError();
e.initCause(e);
throw error;
}
}
// in java/org/jhotdraw/samples/pert/figures/TaskFigure.java
Override
public void read(DOMInput in) throws IOException {
double x = in.getAttribute("x", 0d);
double y = in.getAttribute("y", 0d);
double w = in.getAttribute("w", 0d);
double h = in.getAttribute("h", 0d);
setBounds(new Point2D.Double(x, y), new Point2D.Double(x + w, y + h));
readAttributes(in);
in.openElement("model");
in.openElement("name");
setName((String) in.readObject());
in.closeElement();
in.openElement("duration");
setDuration((Integer) in.readObject());
in.closeElement();
in.closeElement();
}
// in java/org/jhotdraw/samples/pert/figures/TaskFigure.java
Override
public void write(DOMOutput out) throws IOException {
Rectangle2D.Double r = getBounds();
out.addAttribute("x", r.x);
out.addAttribute("y", r.y);
writeAttributes(out);
out.openElement("model");
out.openElement("name");
out.writeObject(getName());
out.closeElement();
out.openElement("duration");
out.writeObject(getDuration());
out.closeElement();
out.closeElement();
}
// in java/org/jhotdraw/samples/pert/PertApplet.java
Override
public void init() {
// Set look and feel
// -----------------
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Throwable e) {
// Do nothing.
// If we can't set the desired look and feel, UIManager does
// automaticaly the right thing for us.
}
// Set our own popup factory, because the one that comes with Mac OS X
// creates translucent popups which is not useful for color selection
// using pop menus.
try {
PopupFactory.setSharedInstance(new PopupFactory());
} catch (Throwable e) {
// If we can't set the popup factory, we have to use what is there.
}
// Display copyright info while we are loading the data
// ----------------------------------------------------
Container c = getContentPane();
c.setLayout(new BoxLayout(c, BoxLayout.Y_AXIS));
String[] labels = getAppletInfo().split("\n");//Strings.split(getAppletInfo(), '\n');
for (int i = 0; i < labels.length; i++) {
c.add(new JLabel((labels[i].length() == 0) ? " " : labels[i]));
}
// We load the data using a worker thread
// --------------------------------------
new Worker<Drawing>() {
@Override
public Drawing construct() throws IOException {
Drawing result;
System.out.println("getParameter.datafile:" + getParameter("datafile"));
if (getParameter("data") != null) {
NanoXMLDOMInput domi = new NanoXMLDOMInput(new PertFactory(), new StringReader(getParameter("data")));
result = (Drawing) domi.readObject(0);
} else if (getParameter("datafile") != null) {
URL url = new URL(getDocumentBase(), getParameter("datafile"));
InputStream in = url.openConnection().getInputStream();
try {
NanoXMLDOMInput domi = new NanoXMLDOMInput(new PertFactory(), in);
result = (Drawing) domi.readObject(0);
} finally {
in.close();
}
} else {
result = null;
}
return result;
}
@Override
protected void done(Drawing result) {
Container c = getContentPane();
c.setLayout(new BorderLayout());
c.removeAll();
c.add(drawingPanel = new PertPanel());
initComponents();
if (result != null) {
setDrawing(result);
}
}
@Override
protected void failed(Throwable value) {
Container c = getContentPane();
c.setLayout(new BorderLayout());
c.removeAll();
c.add(drawingPanel = new PertPanel());
value.printStackTrace();
initComponents();
getDrawing().add(new TextFigure(value.toString()));
value.printStackTrace();
}
@Override
protected void finished() {
Container c = getContentPane();
initDrawing(getDrawing());
c.validate();
}
}.start();
}
// in java/org/jhotdraw/samples/pert/PertApplet.java
Override
public Drawing construct() throws IOException {
Drawing result;
System.out.println("getParameter.datafile:" + getParameter("datafile"));
if (getParameter("data") != null) {
NanoXMLDOMInput domi = new NanoXMLDOMInput(new PertFactory(), new StringReader(getParameter("data")));
result = (Drawing) domi.readObject(0);
} else if (getParameter("datafile") != null) {
URL url = new URL(getDocumentBase(), getParameter("datafile"));
InputStream in = url.openConnection().getInputStream();
try {
NanoXMLDOMInput domi = new NanoXMLDOMInput(new PertFactory(), in);
result = (Drawing) domi.readObject(0);
} finally {
in.close();
}
} else {
result = null;
}
return result;
}
// in java/org/jhotdraw/samples/mini/DefaultDOMStorableSample.java
Override
public void write(DOMOutput out) throws IOException {
out.addAttribute("name", name);
}
// in java/org/jhotdraw/samples/mini/DefaultDOMStorableSample.java
Override
public void read(DOMInput in) throws IOException {
name = in.getAttribute("name", null);
}
// in java/org/jhotdraw/samples/mini/SVGDrawingPanelSample.java
private void open(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_open
JFileChooser fc = getOpenChooser();
if (file != null) {
fc.setSelectedFile(file);
}
if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
svgPanel.setEnabled(false);
final File selectedFile = fc.getSelectedFile();
final InputFormat selectedFormat = fileFilterInputFormatMap.get(fc.getFileFilter());
new Worker() {
@Override
protected Object construct() throws IOException {
svgPanel.read(selectedFile.toURI(), selectedFormat);
return null;
}
@Override
protected void done(Object value) {
file = selectedFile;
setTitle(file.getName());
}
@Override
protected void failed(Throwable error) {
error.printStackTrace();
JOptionPane.showMessageDialog(SVGDrawingPanelSample.this,
"<html><b>Couldn't open file \"" + selectedFile.getName() + "\"<br>" +
error.toString(), "Open File", JOptionPane.ERROR_MESSAGE);
}
@Override
protected void finished() {
svgPanel.setEnabled(true);
}
}.start();
}
}
// in java/org/jhotdraw/samples/mini/SVGDrawingPanelSample.java
Override
protected Object construct() throws IOException {
svgPanel.read(selectedFile.toURI(), selectedFormat);
return null;
}
// in java/org/jhotdraw/samples/mini/SVGDrawingPanelSample.java
private void saveAs(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveAs
JFileChooser fc = getSaveChooser();
if (file != null) {
fc.setSelectedFile(file);
}
if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
svgPanel.setEnabled(false);
final File selectedFile;
if (fc.getFileFilter() instanceof ExtensionFileFilter) {
selectedFile = ((ExtensionFileFilter) fc.getFileFilter()).makeAcceptable(fc.getSelectedFile());
} else {
selectedFile = fc.getSelectedFile();
}
final OutputFormat selectedFormat = fileFilterOutputFormatMap.get(fc.getFileFilter());
new Worker() {
@Override
protected Object construct() throws IOException {
svgPanel.write(selectedFile.toURI(), selectedFormat);
return null;
}
@Override
protected void done(Object value) {
file = selectedFile;
setTitle(file.getName());
}
@Override
protected void failed(Throwable error) {
error.printStackTrace();
JOptionPane.showMessageDialog(SVGDrawingPanelSample.this,
"<html><b>Couldn't save to file \"" + selectedFile.getName() + "\"<br>" +
error.toString(), "Save As File", JOptionPane.ERROR_MESSAGE);
}
@Override
protected void finished() {
svgPanel.setEnabled(true);
}
}.start();
}
}
// in java/org/jhotdraw/samples/mini/SVGDrawingPanelSample.java
Override
protected Object construct() throws IOException {
svgPanel.write(selectedFile.toURI(), selectedFormat);
return null;
}
// in java/org/jhotdraw/samples/net/NetApplet.java
Override
public void init() {
// Set look and feel
// -----------------
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Throwable e) {
// Do nothing.
// If we can't set the desired look and feel, UIManager does
// automaticaly the right thing for us.
}
// Set our own popup factory, because the one that comes with Mac OS X
// creates translucent popups which is not useful for color selection
// using pop menus.
try {
PopupFactory.setSharedInstance(new PopupFactory());
} catch (Throwable e) {
// If we can't set the popup factory, we have to use what is there.
}
// Display copyright info while we are loading the data
// ----------------------------------------------------
Container c = getContentPane();
c.setLayout(new BoxLayout(c, BoxLayout.Y_AXIS));
String[] labels = getAppletInfo().split("\n");//Strings.split(getAppletInfo(), '\n');
for (int i = 0; i < labels.length; i++) {
c.add(new JLabel((labels[i].length() == 0) ? " " : labels[i]));
}
// We load the data using a worker thread
// --------------------------------------
new Worker<Drawing>() {
@Override
protected Drawing construct() throws IOException {
Drawing result;
System.out.println("getParameter.datafile:" + getParameter("datafile"));
if (getParameter("data") != null) {
NanoXMLDOMInput domi = new NanoXMLDOMInput(new NetFactory(), new StringReader(getParameter("data")));
result = (Drawing) domi.readObject(0);
} else if (getParameter("datafile") != null) {
URL url = new URL(getDocumentBase(), getParameter("datafile"));
InputStream in = url.openConnection().getInputStream();
try {
NanoXMLDOMInput domi = new NanoXMLDOMInput(new NetFactory(), in);
result = (Drawing) domi.readObject(0);
} finally {
in.close();
}
} else {
result = null;
}
return result;
}
@Override
protected void done(Drawing result) {
Container c = getContentPane();
c.setLayout(new BorderLayout());
c.removeAll();
c.add(drawingPanel = new NetPanel());
if (result != null) {
Drawing drawing = (Drawing) result;
setDrawing(drawing);
}
}
@Override
protected void failed(Throwable value) {
Container c = getContentPane();
c.setLayout(new BorderLayout());
c.removeAll();
c.add(drawingPanel = new NetPanel());
value.printStackTrace();
getDrawing().add(new TextFigure(value.toString()));
value.printStackTrace();
}
@Override
protected void finished() {
Container c = getContentPane();
initDrawing(getDrawing());
c.validate();
}
}.start();
}
// in java/org/jhotdraw/samples/net/NetApplet.java
Override
protected Drawing construct() throws IOException {
Drawing result;
System.out.println("getParameter.datafile:" + getParameter("datafile"));
if (getParameter("data") != null) {
NanoXMLDOMInput domi = new NanoXMLDOMInput(new NetFactory(), new StringReader(getParameter("data")));
result = (Drawing) domi.readObject(0);
} else if (getParameter("datafile") != null) {
URL url = new URL(getDocumentBase(), getParameter("datafile"));
InputStream in = url.openConnection().getInputStream();
try {
NanoXMLDOMInput domi = new NanoXMLDOMInput(new NetFactory(), in);
result = (Drawing) domi.readObject(0);
} finally {
in.close();
}
} else {
result = null;
}
return result;
}
// in java/org/jhotdraw/samples/net/NetView.java
Override
public void write(URI f, URIChooser chooser) throws IOException {
Drawing drawing = view.getDrawing();
OutputFormat outputFormat = drawing.getOutputFormats().get(0);
outputFormat.write(f, drawing);
}
// in java/org/jhotdraw/samples/net/NetView.java
Override
public void read(URI f, URIChooser chooser) throws IOException {
try {
final Drawing drawing = createDrawing();
InputFormat inputFormat = drawing.getInputFormats().get(0);
inputFormat.read(f, drawing, true);
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
view.getDrawing().removeUndoableEditListener(undo);
view.setDrawing(drawing);
view.getDrawing().addUndoableEditListener(undo);
undo.discardAllEdits();
}
});
} catch (InterruptedException e) {
InternalError error = new InternalError();
e.initCause(e);
throw error;
} catch (InvocationTargetException e) {
InternalError error = new InternalError();
e.initCause(e);
throw error;
}
}
// in java/org/jhotdraw/samples/net/figures/NodeFigure.java
Override
protected void writeDecorator(DOMOutput out) throws IOException {
// do nothing
}
// in java/org/jhotdraw/samples/net/figures/NodeFigure.java
Override
protected void readDecorator(DOMInput in) throws IOException {
// do nothing
}
// in java/org/jhotdraw/samples/svg/SVGApplet.java
protected Drawing loadDrawing(ProgressIndicator progress) throws IOException {
Drawing drawing = createDrawing();
if (getParameter("datafile") != null) {
URL url = new URL(getDocumentBase(), getParameter("datafile"));
URLConnection uc = url.openConnection();
// Disable caching. This ensures that we always request the
// newest version of the drawing from the server.
// (Note: The server still needs to set the proper HTTP caching
// properties to prevent proxies from caching the drawing).
if (uc instanceof HttpURLConnection) {
((HttpURLConnection) uc).setUseCaches(false);
}
// Read the data into a buffer
int contentLength = uc.getContentLength();
InputStream in = uc.getInputStream();
try {
if (contentLength != -1) {
in = new BoundedRangeInputStream(in);
((BoundedRangeInputStream) in).setMaximum(contentLength + 1);
progress.setProgressModel((BoundedRangeModel) in);
progress.setIndeterminate(false);
}
BufferedInputStream bin = new BufferedInputStream(in);
bin.mark(512);
// Read the data using all supported input formats
// until we succeed
IOException formatException = null;
for (InputFormat format : drawing.getInputFormats()) {
try {
bin.reset();
} catch (IOException e) {
uc = url.openConnection();
in = uc.getInputStream();
in = new BoundedRangeInputStream(in);
((BoundedRangeInputStream) in).setMaximum(contentLength + 1);
progress.setProgressModel((BoundedRangeModel) in);
bin = new BufferedInputStream(in);
bin.mark(512);
}
try {
bin.reset();
format.read(bin, drawing, true);
formatException = null;
break;
} catch (IOException e) {
formatException = e;
}
}
if (formatException != null) {
throw formatException;
}
} finally {
in.close();
}
}
return drawing;
}
// in java/org/jhotdraw/samples/svg/figures/SVGImageFigure.java
Override
public void loadImage(File file) throws IOException {
InputStream in = new FileInputStream(file);
try {
loadImage(in);
} catch (Throwable t) {
ResourceBundleUtil labels = ResourceBundleUtil.getBundle("org.jhotdraw.draw.Labels");
IOException e = new IOException(labels.getFormatted("file.failedToLoadImage.message", file.getName()));
e.initCause(t);
throw e;
} finally {
in.close();
}
}
// in java/org/jhotdraw/samples/svg/figures/SVGImageFigure.java
Override
public void loadImage(InputStream in) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[512];
int bytesRead;
while ((bytesRead = in.read(buf)) > 0) {
baos.write(buf, 0, bytesRead);
}
BufferedImage img;
try {
img = ImageIO.read(new ByteArrayInputStream(baos.toByteArray()));
} catch (Throwable t) {
img = null;
}
if (img == null) {
ResourceBundleUtil labels = ResourceBundleUtil.getBundle("org.jhotdraw.draw.Labels");
throw new IOException(labels.getFormatted("file.failedToLoadImage.message", in.toString()));
}
imageData = baos.toByteArray();
bufferedImage = img;
}
// in java/org/jhotdraw/samples/svg/io/SVGZInputFormat.java
Override public void read(InputStream in, Drawing drawing, boolean replace) throws IOException {
BufferedInputStream bin = (in instanceof BufferedInputStream) ? (BufferedInputStream) in : new BufferedInputStream(in);
bin.mark(2);
int magic = (bin.read() & 0xff) | ((bin.read() & 0xff) << 8);
bin.reset();
if (magic == GZIPInputStream.GZIP_MAGIC) {
super.read(new GZIPInputStream(bin), drawing, replace);
} else {
super.read(bin, drawing, replace);
}
}
// in java/org/jhotdraw/samples/svg/io/SVGOutputFormat.java
protected void writeElement(IXMLElement parent, Figure f) throws IOException {
// Write link attribute as encosing "a" element
if (f.get(LINK) != null && f.get(LINK).trim().length() > 0) {
IXMLElement aElement = parent.createElement("a");
aElement.setAttribute("xlink:href", f.get(LINK));
if (f.get(LINK_TARGET) != null && f.get(LINK).trim().length() > 0) {
aElement.setAttribute("target", f.get(LINK_TARGET));
}
parent.addChild(aElement);
parent = aElement;
}
// Write the actual element
if (f instanceof SVGEllipseFigure) {
SVGEllipseFigure ellipse = (SVGEllipseFigure) f;
if (ellipse.getWidth() == ellipse.getHeight()) {
writeCircleElement(parent, ellipse);
} else {
writeEllipseElement(parent, ellipse);
}
} else if (f instanceof SVGGroupFigure) {
writeGElement(parent, (SVGGroupFigure) f);
} else if (f instanceof SVGImageFigure) {
writeImageElement(parent, (SVGImageFigure) f);
} else if (f instanceof SVGPathFigure) {
SVGPathFigure path = (SVGPathFigure) f;
if (path.getChildCount() == 1) {
BezierFigure bezier = (BezierFigure) path.getChild(0);
boolean isLinear = true;
for (int i = 0, n = bezier.getNodeCount(); i < n; i++) {
if (bezier.getNode(i).getMask() != 0) {
isLinear = false;
break;
}
}
if (isLinear) {
if (bezier.isClosed()) {
writePolygonElement(parent, path);
} else {
if (bezier.getNodeCount() == 2) {
writeLineElement(parent, path);
} else {
writePolylineElement(parent, path);
}
}
} else {
writePathElement(parent, path);
}
} else {
writePathElement(parent, path);
}
} else if (f instanceof SVGRectFigure) {
writeRectElement(parent, (SVGRectFigure) f);
} else if (f instanceof SVGTextFigure) {
writeTextElement(parent, (SVGTextFigure) f);
} else if (f instanceof SVGTextAreaFigure) {
writeTextAreaElement(parent, (SVGTextAreaFigure) f);
} else {
System.out.println("Unable to write: " + f);
}
}
// in java/org/jhotdraw/samples/svg/io/SVGOutputFormat.java
protected void writeCircleElement(IXMLElement parent, SVGEllipseFigure f) throws IOException {
parent.addChild(
createCircle(
document,
f.getX() + f.getWidth() / 2d,
f.getY() + f.getHeight() / 2d,
f.getWidth() / 2d,
f.getAttributes()));
}
// in java/org/jhotdraw/samples/svg/io/SVGOutputFormat.java
protected IXMLElement createCircle(IXMLElement doc,
double cx, double cy, double r,
Map<AttributeKey, Object> attributes) throws IOException {
IXMLElement elem = doc.createElement("circle");
writeAttribute(elem, "cx", cx, 0d);
writeAttribute(elem, "cy", cy, 0d);
writeAttribute(elem, "r", r, 0d);
writeShapeAttributes(elem, attributes);
writeOpacityAttribute(elem, attributes);
writeTransformAttribute(elem, attributes);
return elem;
}
// in java/org/jhotdraw/samples/svg/io/SVGOutputFormat.java
protected IXMLElement createG(IXMLElement doc,
Map<AttributeKey, Object> attributes) throws IOException {
IXMLElement elem = doc.createElement("g");
writeOpacityAttribute(elem, attributes);
return elem;
}
// in java/org/jhotdraw/samples/svg/io/SVGOutputFormat.java
protected IXMLElement createLinearGradient(IXMLElement doc,
double x1, double y1, double x2, double y2,
double[] stopOffsets, Color[] stopColors, double[] stopOpacities,
boolean isRelativeToFigureBounds,
AffineTransform transform) throws IOException {
IXMLElement elem = doc.createElement("linearGradient");
writeAttribute(elem, "x1", toNumber(x1), "0");
writeAttribute(elem, "y1", toNumber(y1), "0");
writeAttribute(elem, "x2", toNumber(x2), "1");
writeAttribute(elem, "y2", toNumber(y2), "0");
writeAttribute(elem, "gradientUnits",
(isRelativeToFigureBounds) ? "objectBoundingBox" : "userSpaceOnUse",
"objectBoundingBox");
writeAttribute(elem, "gradientTransform", toTransform(transform), "none");
for (int i = 0; i < stopOffsets.length; i++) {
IXMLElement stop = new XMLElement("stop");
writeAttribute(stop, "offset", toNumber(stopOffsets[i]), null);
writeAttribute(stop, "stop-color", toColor(stopColors[i]), null);
writeAttribute(stop, "stop-opacity", toNumber(stopOpacities[i]), "1");
elem.addChild(stop);
}
return elem;
}
// in java/org/jhotdraw/samples/svg/io/SVGOutputFormat.java
protected IXMLElement createRadialGradient(IXMLElement doc,
double cx, double cy, double fx, double fy, double r,
double[] stopOffsets, Color[] stopColors, double[] stopOpacities,
boolean isRelativeToFigureBounds,
AffineTransform transform) throws IOException {
IXMLElement elem = doc.createElement("radialGradient");
writeAttribute(elem, "cx", toNumber(cx), "0.5");
writeAttribute(elem, "cy", toNumber(cy), "0.5");
writeAttribute(elem, "fx", toNumber(fx), toNumber(cx));
writeAttribute(elem, "fy", toNumber(fy), toNumber(cy));
writeAttribute(elem, "r", toNumber(r), "0.5");
writeAttribute(elem, "gradientUnits",
(isRelativeToFigureBounds) ? "objectBoundingBox" : "userSpaceOnUse",
"objectBoundingBox");
writeAttribute(elem, "gradientTransform", toTransform(transform), "none");
for (int i = 0; i < stopOffsets.length; i++) {
IXMLElement stop = new XMLElement("stop");
writeAttribute(stop, "offset", toNumber(stopOffsets[i]), null);
writeAttribute(stop, "stop-color", toColor(stopColors[i]), null);
writeAttribute(stop, "stop-opacity", toNumber(stopOpacities[i]), "1");
elem.addChild(stop);
}
return elem;
}
// in java/org/jhotdraw/samples/svg/io/SVGOutputFormat.java
protected void writeEllipseElement(IXMLElement parent, SVGEllipseFigure f) throws IOException {
parent.addChild(createEllipse(
document,
f.getX() + f.getWidth() / 2d,
f.getY() + f.getHeight() / 2d,
f.getWidth() / 2d,
f.getHeight() / 2d,
f.getAttributes()));
}
// in java/org/jhotdraw/samples/svg/io/SVGOutputFormat.java
protected IXMLElement createEllipse(IXMLElement doc,
double cx, double cy, double rx, double ry,
Map<AttributeKey, Object> attributes) throws IOException {
IXMLElement elem = doc.createElement("ellipse");
writeAttribute(elem, "cx", cx, 0d);
writeAttribute(elem, "cy", cy, 0d);
writeAttribute(elem, "rx", rx, 0d);
writeAttribute(elem, "ry", ry, 0d);
writeShapeAttributes(elem, attributes);
writeOpacityAttribute(elem, attributes);
writeTransformAttribute(elem, attributes);
return elem;
}
// in java/org/jhotdraw/samples/svg/io/SVGOutputFormat.java
protected void writeGElement(IXMLElement parent, SVGGroupFigure f) throws IOException {
IXMLElement elem = createG(document, f.getAttributes());
for (Figure child : f.getChildren()) {
writeElement(elem, child);
}
parent.addChild(elem);
}
// in java/org/jhotdraw/samples/svg/io/SVGOutputFormat.java
protected void writeImageElement(IXMLElement parent, SVGImageFigure f) throws IOException {
parent.addChild(
createImage(document,
f.getX(),
f.getY(),
f.getWidth(),
f.getHeight(),
f.getImageData(),
f.getAttributes()));
}
// in java/org/jhotdraw/samples/svg/io/SVGOutputFormat.java
protected IXMLElement createImage(IXMLElement doc,
double x, double y, double w, double h,
byte[] imageData,
Map<AttributeKey, Object> attributes) throws IOException {
IXMLElement elem = doc.createElement("image");
writeAttribute(elem, "x", x, 0d);
writeAttribute(elem, "y", y, 0d);
writeAttribute(elem, "width", w, 0d);
writeAttribute(elem, "height", h, 0d);
writeAttribute(elem, "xlink:href", "data:image;base64," + Base64.encodeBytes(imageData), "");
writeOpacityAttribute(elem, attributes);
writeTransformAttribute(elem, attributes);
return elem;
}
// in java/org/jhotdraw/samples/svg/io/SVGOutputFormat.java
protected void writePathElement(IXMLElement parent, SVGPathFigure f) throws IOException {
BezierPath[] beziers = new BezierPath[f.getChildCount()];
for (int i = 0; i < beziers.length; i++) {
beziers[i] = ((BezierFigure) f.getChild(i)).getBezierPath();
}
parent.addChild(createPath(
document,
beziers,
f.getAttributes()));
}
// in java/org/jhotdraw/samples/svg/io/SVGOutputFormat.java
protected IXMLElement createPath(IXMLElement doc,
BezierPath[] beziers,
Map<AttributeKey, Object> attributes) throws IOException {
IXMLElement elem = doc.createElement("path");
writeShapeAttributes(elem, attributes);
writeOpacityAttribute(elem, attributes);
writeTransformAttribute(elem, attributes);
writeAttribute(elem, "d", toPath(beziers), null);
return elem;
}
// in java/org/jhotdraw/samples/svg/io/SVGOutputFormat.java
protected void writePolygonElement(IXMLElement parent, SVGPathFigure f) throws IOException {
LinkedList<Point2D.Double> points = new LinkedList<Point2D.Double>();
for (int i = 0, n = f.getChildCount(); i < n; i++) {
BezierPath bezier = ((BezierFigure) f.getChild(i)).getBezierPath();
for (BezierPath.Node node : bezier) {
points.add(new Point2D.Double(node.x[0], node.y[0]));
}
}
parent.addChild(createPolygon(
document,
points.toArray(new Point2D.Double[points.size()]),
f.getAttributes()));
}
// in java/org/jhotdraw/samples/svg/io/SVGOutputFormat.java
protected IXMLElement createPolygon(IXMLElement doc,
Point2D.Double[] points,
Map<AttributeKey, Object> attributes)
throws IOException {
IXMLElement elem = doc.createElement("polygon");
writeAttribute(elem, "points", toPoints(points), null);
writeShapeAttributes(elem, attributes);
writeOpacityAttribute(elem, attributes);
writeTransformAttribute(elem, attributes);
return elem;
}
// in java/org/jhotdraw/samples/svg/io/SVGOutputFormat.java
protected void writePolylineElement(IXMLElement parent, SVGPathFigure f) throws IOException {
LinkedList<Point2D.Double> points = new LinkedList<Point2D.Double>();
for (int i = 0, n = f.getChildCount(); i < n; i++) {
BezierPath bezier = ((BezierFigure) f.getChild(i)).getBezierPath();
for (BezierPath.Node node : bezier) {
points.add(new Point2D.Double(node.x[0], node.y[0]));
}
}
parent.addChild(createPolyline(
document,
points.toArray(new Point2D.Double[points.size()]),
f.getAttributes()));
}
// in java/org/jhotdraw/samples/svg/io/SVGOutputFormat.java
protected IXMLElement createPolyline(IXMLElement doc,
Point2D.Double[] points,
Map<AttributeKey, Object> attributes) throws IOException {
IXMLElement elem = doc.createElement("polyline");
writeAttribute(elem, "points", toPoints(points), null);
writeShapeAttributes(elem, attributes);
writeOpacityAttribute(elem, attributes);
writeTransformAttribute(elem, attributes);
return elem;
}
// in java/org/jhotdraw/samples/svg/io/SVGOutputFormat.java
protected void writeLineElement(IXMLElement parent, SVGPathFigure f)
throws IOException {
BezierFigure bezier = (BezierFigure) f.getChild(0);
parent.addChild(createLine(
document,
bezier.getNode(0).x[0],
bezier.getNode(0).y[0],
bezier.getNode(1).x[0],
bezier.getNode(1).y[0],
f.getAttributes()));
}
// in java/org/jhotdraw/samples/svg/io/SVGOutputFormat.java
protected IXMLElement createLine(IXMLElement doc,
double x1, double y1, double x2, double y2,
Map<AttributeKey, Object> attributes) throws IOException {
IXMLElement elem = doc.createElement("line");
writeAttribute(elem, "x1", x1, 0d);
writeAttribute(elem, "y1", y1, 0d);
writeAttribute(elem, "x2", x2, 0d);
writeAttribute(elem, "y2", y2, 0d);
writeShapeAttributes(elem, attributes);
writeOpacityAttribute(elem, attributes);
writeTransformAttribute(elem, attributes);
return elem;
}
// in java/org/jhotdraw/samples/svg/io/SVGOutputFormat.java
protected void writeRectElement(IXMLElement parent, SVGRectFigure f) throws IOException {
parent.addChild(
createRect(
document,
f.getX(),
f.getY(),
f.getWidth(),
f.getHeight(),
f.getArcWidth(),
f.getArcHeight(),
f.getAttributes()));
}
// in java/org/jhotdraw/samples/svg/io/SVGOutputFormat.java
protected IXMLElement createRect(IXMLElement doc,
double x, double y, double width, double height,
double rx, double ry,
Map<AttributeKey, Object> attributes)
throws IOException {
IXMLElement elem = doc.createElement("rect");
writeAttribute(elem, "x", x, 0d);
writeAttribute(elem, "y", y, 0d);
writeAttribute(elem, "width", width, 0d);
writeAttribute(elem, "height", height, 0d);
writeAttribute(elem, "rx", rx, 0d);
writeAttribute(elem, "ry", ry, 0d);
writeShapeAttributes(elem, attributes);
writeOpacityAttribute(elem, attributes);
writeTransformAttribute(elem, attributes);
return elem;
}
// in java/org/jhotdraw/samples/svg/io/SVGOutputFormat.java
protected void writeTextElement(IXMLElement parent, SVGTextFigure f) throws IOException {
DefaultStyledDocument styledDoc = new DefaultStyledDocument();
try {
styledDoc.insertString(0, f.getText(), null);
} catch (BadLocationException e) {
InternalError error = new InternalError(e.getMessage());
error.initCause(e);
throw error;
}
parent.addChild(
createText(
document,
f.getCoordinates(),
f.getRotates(),
styledDoc,
f.getAttributes()));
}
// in java/org/jhotdraw/samples/svg/io/SVGOutputFormat.java
protected IXMLElement createText(IXMLElement doc,
Point2D.Double[] coordinates, double[] rotate,
StyledDocument text,
Map<AttributeKey, Object> attributes) throws IOException {
IXMLElement elem = doc.createElement("text");
StringBuilder bufX = new StringBuilder();
StringBuilder bufY = new StringBuilder();
for (int i = 0; i < coordinates.length; i++) {
if (i != 0) {
bufX.append(',');
bufY.append(',');
}
bufX.append(toNumber(coordinates[i].getX()));
bufY.append(toNumber(coordinates[i].getY()));
}
StringBuilder bufR = new StringBuilder();
if (rotate != null) {
for (int i = 0; i < rotate.length; i++) {
if (i != 0) {
bufR.append(',');
}
bufR.append(toNumber(rotate[i]));
}
}
writeAttribute(elem, "x", bufX.toString(), "0");
writeAttribute(elem, "y", bufY.toString(), "0");
writeAttribute(elem, "rotate", bufR.toString(), "");
String str;
try {
str = text.getText(0, text.getLength());
} catch (BadLocationException e) {
InternalError error = new InternalError(e.getMessage());
error.initCause(e);
throw error;
}
elem.setContent(str);
writeShapeAttributes(elem, attributes);
writeOpacityAttribute(elem, attributes);
writeTransformAttribute(elem, attributes);
writeFontAttributes(elem, attributes);
return elem;
}
// in java/org/jhotdraw/samples/svg/io/SVGOutputFormat.java
protected void writeTextAreaElement(IXMLElement parent, SVGTextAreaFigure f)
throws IOException {
DefaultStyledDocument styledDoc = new DefaultStyledDocument();
try {
styledDoc.insertString(0, f.getText(), null);
} catch (BadLocationException e) {
InternalError error = new InternalError(e.getMessage());
error.initCause(e);
throw error;
}
Rectangle2D.Double bounds = f.getBounds();
parent.addChild(
createTextArea(
document,
bounds.x, bounds.y, bounds.width, bounds.height,
styledDoc,
f.getAttributes()));
}
// in java/org/jhotdraw/samples/svg/io/SVGOutputFormat.java
protected IXMLElement createTextArea(IXMLElement doc,
double x, double y, double w, double h,
StyledDocument text,
Map<AttributeKey, Object> attributes)
throws IOException {
IXMLElement elem = doc.createElement("textArea");
writeAttribute(elem, "x", toNumber(x), "0");
writeAttribute(elem, "y", toNumber(y), "0");
writeAttribute(elem, "width", toNumber(w), "0");
writeAttribute(elem, "height", toNumber(h), "0");
String str;
try {
str = text.getText(0, text.getLength());
} catch (BadLocationException e) {
InternalError error = new InternalError(e.getMessage());
error.initCause(e);
throw error;
}
String[] lines = str.split("\n");
for (int i = 0; i < lines.length; i++) {
if (i != 0) {
elem.addChild(doc.createElement("tbreak"));
}
IXMLElement contentElement = doc.createElement(null);
contentElement.setContent(lines[i]);
elem.addChild(contentElement);
}
writeShapeAttributes(elem, attributes);
writeTransformAttribute(elem, attributes);
writeOpacityAttribute(elem, attributes);
writeFontAttributes(elem, attributes);
return elem;
}
// in java/org/jhotdraw/samples/svg/io/SVGOutputFormat.java
protected void writeShapeAttributes(IXMLElement elem, Map<AttributeKey, Object> m)
throws IOException {
Color color;
String value;
int intValue;
//'color'
// Value: <color> | inherit
// Initial: depends on user agent
// Applies to: None. Indirectly affects other properties via currentColor
// Inherited: yes
// Percentages: N/A
// Media: visual
// Animatable: yes
// Computed value: Specified <color> value, except inherit
//
// Nothing to do: Attribute 'color' is not needed.
//'color-rendering'
// Value: auto | optimizeSpeed | optimizeQuality | inherit
// Initial: auto
// Applies to: container elements , graphics elements and 'animateColor'
// Inherited: yes
// Percentages: N/A
// Media: visual
// Animatable: yes
// Computed value: Specified value, except inherit
//
// Nothing to do: Attribute 'color-rendering' is not needed.
// 'fill'
// Value: <paint> | inherit (See Specifying paint)
// Initial: black
// Applies to: shapes and text content elements
// Inherited: yes
// Percentages: N/A
// Media: visual
// Animatable: yes
// Computed value: "none", system paint, specified <color> value or absolute IRI
Gradient gradient = FILL_GRADIENT.get(m);
if (gradient != null) {
String id;
if (gradientToIDMap.containsKey(gradient)) {
id = gradientToIDMap.get(gradient);
} else {
IXMLElement gradientElem;
if (gradient instanceof LinearGradient) {
LinearGradient lg = (LinearGradient) gradient;
gradientElem = createLinearGradient(document,
lg.getX1(), lg.getY1(),
lg.getX2(), lg.getY2(),
lg.getStopOffsets(),
lg.getStopColors(),
lg.getStopOpacities(),
lg.isRelativeToFigureBounds(),
lg.getTransform());
} else /*if (gradient instanceof RadialGradient)*/ {
RadialGradient rg = (RadialGradient) gradient;
gradientElem = createRadialGradient(document,
rg.getCX(), rg.getCY(),
rg.getFX(), rg.getFY(),
rg.getR(),
rg.getStopOffsets(),
rg.getStopColors(),
rg.getStopOpacities(),
rg.isRelativeToFigureBounds(),
rg.getTransform());
}
id = getId(gradientElem);
gradientElem.setAttribute("id", "xml", id);
defs.addChild(gradientElem);
gradientToIDMap.put(gradient, id);
}
writeAttribute(elem, "fill", "url(#" + id + ")", "#000");
} else {
writeAttribute(elem, "fill", toColor(FILL_COLOR.get(m)), "#000");
}
//'fill-opacity'
//Value: <opacity-value> | inherit
//Initial: 1
//Applies to: shapes and text content elements
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
writeAttribute(elem, "fill-opacity", FILL_OPACITY.get(m), 1d);
// 'fill-rule'
// Value: nonzero | evenodd | inherit
// Initial: nonzero
// Applies to: shapes and text content elements
// Inherited: yes
// Percentages: N/A
// Media: visual
// Animatable: yes
// Computed value: Specified value, except inherit
if (WINDING_RULE.get(m) != WindingRule.NON_ZERO) {
writeAttribute(elem, "fill-rule", "evenodd", "nonzero");
}
//'stroke'
//Value: <paint> | inherit (See Specifying paint)
//Initial: none
//Applies to: shapes and text content elements
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: "none", system paint, specified <color> value
// or absolute IRI
gradient = STROKE_GRADIENT.get(m);
if (gradient != null) {
String id;
if (gradientToIDMap.containsKey(gradient)) {
id = gradientToIDMap.get(gradient);
} else {
IXMLElement gradientElem;
if (gradient instanceof LinearGradient) {
LinearGradient lg = (LinearGradient) gradient;
gradientElem = createLinearGradient(document,
lg.getX1(), lg.getY1(),
lg.getX2(), lg.getY2(),
lg.getStopOffsets(),
lg.getStopColors(),
lg.getStopOpacities(),
lg.isRelativeToFigureBounds(),
lg.getTransform());
} else /*if (gradient instanceof RadialGradient)*/ {
RadialGradient rg = (RadialGradient) gradient;
gradientElem = createRadialGradient(document,
rg.getCX(), rg.getCY(),
rg.getFX(), rg.getFY(),
rg.getR(),
rg.getStopOffsets(),
rg.getStopColors(),
rg.getStopOpacities(),
rg.isRelativeToFigureBounds(),
rg.getTransform());
}
id = getId(gradientElem);
gradientElem.setAttribute("id", "xml", id);
defs.addChild(gradientElem);
gradientToIDMap.put(gradient, id);
}
writeAttribute(elem, "stroke", "url(#" + id + ")", "none");
} else {
writeAttribute(elem, "stroke", toColor(STROKE_COLOR.get(m)), "none");
}
//'stroke-dasharray'
//Value: none | <dasharray> | inherit
//Initial: none
//Applies to: shapes and text content elements
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes (non-additive)
//Computed value: Specified value, except inherit
double[] dashes = STROKE_DASHES.get(m);
if (dashes != null) {
StringBuilder buf = new StringBuilder();
for (int i = 0; i < dashes.length; i++) {
if (i != 0) {
buf.append(',');
}
buf.append(toNumber(dashes[i]));
}
writeAttribute(elem, "stroke-dasharray", buf.toString(), null);
}
//'stroke-dashoffset'
//Value: <length> | inherit
//Initial: 0
//Applies to: shapes and text content elements
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
writeAttribute(elem, "stroke-dashoffset", STROKE_DASH_PHASE.get(m), 0d);
//'stroke-linecap'
//Value: butt | round | square | inherit
//Initial: butt
//Applies to: shapes and text content elements
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
writeAttribute(elem, "stroke-linecap", strokeLinecapMap.get(STROKE_CAP.get(m)), "butt");
//'stroke-linejoin'
//Value: miter | round | bevel | inherit
//Initial: miter
//Applies to: shapes and text content elements
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
writeAttribute(elem, "stroke-linejoin", strokeLinejoinMap.get(STROKE_JOIN.get(m)), "miter");
//'stroke-miterlimit'
//Value: <miterlimit> | inherit
//Initial: 4
//Applies to: shapes and text content elements
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
writeAttribute(elem, "stroke-miterlimit", STROKE_MITER_LIMIT.get(m), 4d);
//'stroke-opacity'
//Value: <opacity-value> | inherit
//Initial: 1
//Applies to: shapes and text content elements
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
writeAttribute(elem, "stroke-opacity", STROKE_OPACITY.get(m), 1d);
//'stroke-width'
//Value: <length> | inherit
//Initial: 1
//Applies to: shapes and text content elements
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
writeAttribute(elem, "stroke-width", STROKE_WIDTH.get(m), 1d);
}
// in java/org/jhotdraw/samples/svg/io/SVGOutputFormat.java
protected void writeOpacityAttribute(IXMLElement elem, Map<AttributeKey, Object> m)
throws IOException {
//'opacity'
//Value: <opacity-value> | inherit
//Initial: 1
//Applies to: 'image' element
//Inherited: no
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
//<opacity-value>
//The uniform opacity setting must be applied across an entire object.
//Any values outside the range 0.0 (fully transparent) to 1.0
//(fully opaque) shall be clamped to this range.
//(See Clamping values which are restricted to a particular range.)
writeAttribute(elem, "opacity", OPACITY.get(m), 1d);
}
// in java/org/jhotdraw/samples/svg/io/SVGOutputFormat.java
protected void writeTransformAttribute(IXMLElement elem, Map<AttributeKey, Object> a)
throws IOException {
AffineTransform t = TRANSFORM.get(a);
if (t != null) {
writeAttribute(elem, "transform", toTransform(t), "none");
}
}
// in java/org/jhotdraw/samples/svg/io/SVGOutputFormat.java
private void writeFontAttributes(IXMLElement elem, Map<AttributeKey, Object> a)
throws IOException {
String value;
double doubleValue;
// 'font-family'
// Value: [[ <family-name> |
// <generic-family> ],]* [<family-name> |
// <generic-family>] | inherit
// Initial: depends on user agent
// Applies to: text content elements
// Inherited: yes
// Percentages: N/A
// Media: visual
// Animatable: yes
// Computed value: Specified value, except inherit
writeAttribute(elem, "font-family", FONT_FACE.get(a).getFontName(), "Dialog");
// 'font-getChildCount'
// Value: <absolute-getChildCount> | <relative-getChildCount> |
// <length> | inherit
// Initial: medium
// Applies to: text content elements
// Inherited: yes, the computed value is inherited
// Percentages: N/A
// Media: visual
// Animatable: yes
// Computed value: Absolute length
writeAttribute(elem, "font-size", FONT_SIZE.get(a), 0d);
// 'font-style'
// Value: normal | italic | oblique | inherit
// Initial: normal
// Applies to: text content elements
// Inherited: yes
// Percentages: N/A
// Media: visual
// Animatable: yes
// Computed value: Specified value, except inherit
writeAttribute(elem, "font-style", (FONT_ITALIC.get(a)) ? "italic" : "normal", "normal");
//'font-variant'
//Value: normal | small-caps | inherit
//Initial: normal
//Applies to: text content elements
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: no
//Computed value: Specified value, except inherit
// XXX - Implement me
writeAttribute(elem, "font-variant", "normal", "normal");
// 'font-weight'
// Value: normal | bold | bolder | lighter | 100 | 200 | 300
// | 400 | 500 | 600 | 700 | 800 | 900 | inherit
// Initial: normal
// Applies to: text content elements
// Inherited: yes
// Percentages: N/A
// Media: visual
// Animatable: yes
// Computed value: one of the legal numeric values, non-numeric
// values shall be converted to numeric values according to the rules
// defined below.
writeAttribute(elem, "font-weight", (FONT_BOLD.get(a)) ? "bold" : "normal", "normal");
// Note: text-decoration is an SVG 1.1 feature
//'text-decoration'
//Value: none | [ underline || overline || line-through || blink ] | inherit
//Initial: none
//Applies to: text content elements
//Inherited: no (see prose)
//Percentages: N/A
//Media: visual
//Animatable: yes
writeAttribute(elem, "text-decoration", (FONT_UNDERLINE.get(a)) ? "underline" : "none", "none");
}
// in java/org/jhotdraw/samples/svg/io/SVGOutputFormat.java
private void writeViewportAttributes(IXMLElement elem, Map<AttributeKey, Object> a)
throws IOException {
Object value;
Double doubleValue;
if (VIEWPORT_WIDTH.get(a) != null && VIEWPORT_HEIGHT.get(a) != null) {
// width of the viewport
writeAttribute(elem, "width", toNumber(VIEWPORT_WIDTH.get(a)), null);
// height of the viewport
writeAttribute(elem, "height", toNumber(VIEWPORT_HEIGHT.get(a)), null);
}
//'viewport-fill'
//Value: "none" | <color> | inherit
//Initial: none
//Applies to: viewport-creating elements
//Inherited: no
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: "none" or specified <color> value, except inherit
writeAttribute(elem, "viewport-fill", toColor(VIEWPORT_FILL.get(a)), "none");
//'viewport-fill-opacity'
//Value: <opacity-value> | inherit
//Initial: 1.0
//Applies to: viewport-creating elements
//Inherited: no
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
writeAttribute(elem, "viewport-fill-opacity", VIEWPORT_FILL_OPACITY.get(a), 1.0);
}
// in java/org/jhotdraw/samples/svg/io/SVGOutputFormat.java
public static String toPoints(Point2D.Double[] points) throws IOException {
StringBuilder buf = new StringBuilder();
for (int i = 0; i < points.length; i++) {
if (i != 0) {
buf.append(", ");
}
buf.append(toNumber(points[i].x));
buf.append(',');
buf.append(toNumber(points[i].y));
}
return buf.toString();
}
// in java/org/jhotdraw/samples/svg/io/SVGOutputFormat.java
public static String toTransform(AffineTransform t) throws IOException {
StringBuilder buf = new StringBuilder();
switch (t.getType()) {
case AffineTransform.TYPE_IDENTITY:
buf.append("none");
break;
case AffineTransform.TYPE_TRANSLATION:
// translate(<tx> [<ty>]), specifies a translation by tx and ty.
// If <ty> is not provided, it is assumed to be zero.
buf.append("translate(");
buf.append(toNumber(t.getTranslateX()));
if (t.getTranslateY() != 0d) {
buf.append(' ');
buf.append(toNumber(t.getTranslateY()));
}
buf.append(')');
break;
/*
case AffineTransform.TYPE_GENERAL_ROTATION :
case AffineTransform.TYPE_QUADRANT_ROTATION :
case AffineTransform.TYPE_MASK_ROTATION :
// rotate(<rotate-angle> [<cx> <cy>]), specifies a rotation by
// <rotate-angle> degrees about a given point.
// If optional parameters <cx> and <cy> are not supplied, the
// rotate is about the origin of the current user coordinate
// system. The operation corresponds to the matrix
// [cos(a) sin(a) -sin(a) cos(a) 0 0].
// If optional parameters <cx> and <cy> are supplied, the rotate
// is about the point (<cx>, <cy>). The operation represents the
// equivalent of the following specification:
// translate(<cx>, <cy>) rotate(<rotate-angle>)
// translate(-<cx>, -<cy>).
buf.append("rotate(");
buf.append(toNumber(t.getScaleX()));
buf.append(')');
break;*/
case AffineTransform.TYPE_UNIFORM_SCALE:
// scale(<sx> [<sy>]), specifies a scale operation by sx
// and sy. If <sy> is not provided, it is assumed to be equal
// to <sx>.
buf.append("scale(");
buf.append(toNumber(t.getScaleX()));
buf.append(')');
break;
case AffineTransform.TYPE_GENERAL_SCALE:
case AffineTransform.TYPE_MASK_SCALE:
// scale(<sx> [<sy>]), specifies a scale operation by sx
// and sy. If <sy> is not provided, it is assumed to be equal
// to <sx>.
buf.append("scale(");
buf.append(toNumber(t.getScaleX()));
buf.append(' ');
buf.append(toNumber(t.getScaleY()));
buf.append(')');
break;
default:
// matrix(<a> <b> <c> <d> <e> <f>), specifies a transformation
// in the form of a transformation matrix of six values.
// matrix(a,b,c,d,e,f) is equivalent to applying the
// transformation matrix [a b c d e f].
buf.append("matrix(");
double[] matrix = new double[6];
t.getMatrix(matrix);
for (int i = 0; i < matrix.length; i++) {
if (i != 0) {
buf.append(' ');
}
buf.append(toNumber(matrix[i]));
}
buf.append(')');
break;
}
return buf.toString();
}
// in java/org/jhotdraw/samples/svg/io/SVGOutputFormat.java
Override
public void write(URI uri, Drawing drawing) throws IOException {
write(new File(uri), drawing);
}
// in java/org/jhotdraw/samples/svg/io/SVGOutputFormat.java
public void write(File file, Drawing drawing) throws IOException {
BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream(file));
try {
write(out, drawing);
} finally {
out.close();
}
}
// in java/org/jhotdraw/samples/svg/io/SVGOutputFormat.java
Override
public void write(OutputStream out, Drawing drawing) throws IOException {
write(out, drawing, drawing.getChildren());
}
// in java/org/jhotdraw/samples/svg/io/SVGOutputFormat.java
public void write(OutputStream out, Drawing drawing, java.util.List<Figure> figures) throws IOException {
document = new XMLElement("svg", SVG_NAMESPACE);
document.setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink");
document.setAttribute("version", "1.2");
document.setAttribute("baseProfile", "tiny");
writeViewportAttributes(document, drawing.getAttributes());
initStorageContext(document);
defs = new XMLElement("defs");
document.addChild(defs);
for (Figure f : figures) {
writeElement(document, f);
}
// Write XML prolog
PrintWriter writer = new PrintWriter(
new OutputStreamWriter(out, "UTF-8"));
writer.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
// Write XML content
XMLWriter xmlWriter = new XMLWriter(writer);
xmlWriter.write(document, isPrettyPrint);
// Flush writer
writer.flush();
document.dispose();
}
// in java/org/jhotdraw/samples/svg/io/SVGOutputFormat.java
Override
public Transferable createTransferable(Drawing drawing, java.util.List<Figure> figures, double scaleFactor) throws IOException {
ByteArrayOutputStream buf = new ByteArrayOutputStream();
write(buf, drawing, figures);
return new InputStreamTransferable(new DataFlavor(SVG_MIMETYPE, "Image SVG"), buf.toByteArray());
}
// in java/org/jhotdraw/samples/svg/io/SVGZOutputFormat.java
Override public void write(OutputStream out, Drawing drawing) throws IOException {
GZIPOutputStream gout = new GZIPOutputStream(out);
super.write(gout, drawing, drawing.getChildren());
gout.finish();
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
Override
public void read(URI uri, Drawing drawing) throws IOException {
read(new File(uri), drawing);
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
Override
public void read(URI uri, Drawing drawing, boolean replace) throws IOException {
read(new File(uri), drawing, replace);
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
public void read(File file, Drawing drawing) throws IOException {
read(file, drawing, true);
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
public void read(File file, Drawing drawing, boolean replace) throws IOException {
this.url = file.toURI().toURL();
BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
try {
read(in, drawing, replace);
} finally {
in.close();
}
this.url = null;
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
public void read(URL url, Drawing drawing, boolean replace) throws IOException {
this.url = url;
InputStream in = url.openStream();
try {
read(in, drawing, replace);
} finally {
in.close();
}
this.url = null;
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
Override
public void read(InputStream in, Drawing drawing, boolean replace) throws IOException {
long start;
if (DEBUG) {
start = System.currentTimeMillis();
}
this.figures = new LinkedList<Figure>();
IXMLParser parser;
try {
parser = XMLParserFactory.createDefaultXMLParser();
} catch (Exception ex) {
InternalError e = new InternalError("Unable to instantiate NanoXML Parser");
e.initCause(ex);
throw e;
}
if (DEBUG) {
System.out.println("SVGInputFormat parser created " + (System.currentTimeMillis() - start));
}
IXMLReader reader = new StdXMLReader(in);
parser.setReader(reader);
if (DEBUG) {
System.out.println("SVGInputFormat reader created " + (System.currentTimeMillis() - start));
}
try {
document = (IXMLElement) parser.parse();
} catch (XMLException ex) {
IOException e = new IOException(ex.getMessage());
e.initCause(ex);
throw e;
}
if (DEBUG) {
System.out.println("SVGInputFormat document created " + (System.currentTimeMillis() - start));
}
// Search for the first 'svg' element in the XML document
// in preorder sequence
IXMLElement svg = document;
Stack<Iterator<IXMLElement>> stack = new Stack<Iterator<IXMLElement>>();
LinkedList<IXMLElement> ll = new LinkedList<IXMLElement>();
ll.add(document);
stack.push(ll.iterator());
while (!stack.empty() && stack.peek().hasNext()) {
Iterator<IXMLElement> iter = stack.peek();
IXMLElement node = iter.next();
Iterator<IXMLElement> children = (node.getChildren() == null) ? null : node.getChildren().iterator();
if (!iter.hasNext()) {
stack.pop();
}
if (children != null && children.hasNext()) {
stack.push(children);
}
if (node.getName() != null
&& node.getName().equals("svg")
&& (node.getNamespace() == null
|| node.getNamespace().equals(SVG_NAMESPACE))) {
svg = node;
break;
}
}
if (svg.getName() == null
|| !svg.getName().equals("svg")
|| (svg.getNamespace() != null
&& !svg.getNamespace().equals(SVG_NAMESPACE))) {
throw new IOException("'svg' element expected: " + svg.getName());
}
//long end1 = System.currentTimeMillis();
// Flatten CSS Styles
initStorageContext(document);
flattenStyles(svg);
//long end2 = System.currentTimeMillis();
readElement(svg);
if (DEBUG) {
long end = System.currentTimeMillis();
System.out.println("SVGInputFormat elapsed:" + (end - start));
}
/*if (DEBUG) System.out.println("SVGInputFormat read:"+(end1-start));
if (DEBUG) System.out.println("SVGInputFormat flatten:"+(end2-end1));
if (DEBUG) System.out.println("SVGInputFormat build:"+(end-end2));
*/
if (replace) {
drawing.removeAllChildren();
}
drawing.addAll(figures);
if (replace) {
Viewport viewport = viewportStack.firstElement();
drawing.set(VIEWPORT_FILL, VIEWPORT_FILL.get(viewport.attributes));
drawing.set(VIEWPORT_FILL_OPACITY, VIEWPORT_FILL_OPACITY.get(viewport.attributes));
drawing.set(VIEWPORT_HEIGHT, VIEWPORT_HEIGHT.get(viewport.attributes));
drawing.set(VIEWPORT_WIDTH, VIEWPORT_WIDTH.get(viewport.attributes));
}
// Get rid of all objects we don't need anymore to help garbage collector.
document.dispose();
identifiedElements.clear();
elementObjects.clear();
viewportStack.clear();
styleManager.clear();
document = null;
identifiedElements = null;
elementObjects = null;
viewportStack = null;
styleManager = null;
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
private void flattenStyles(IXMLElement elem)
throws IOException {
if (elem.getName() != null && elem.getName().equals("style")
&& readAttribute(elem, "type", "").equals("text/css")
&& elem.getContent() != null) {
CSSParser cssParser = new CSSParser();
cssParser.parse(elem.getContent(), styleManager);
} else {
if (elem.getNamespace() == null
|| elem.getNamespace().equals(SVG_NAMESPACE)) {
String style = readAttribute(elem, "style", null);
if (style != null) {
for (String styleProperty : style.split(";")) {
String[] stylePropertyElements = styleProperty.split(":");
if (stylePropertyElements.length == 2
&& !elem.hasAttribute(stylePropertyElements[0].trim(), SVG_NAMESPACE)) {
//if (DEBUG) System.out.println("flatten:"+Arrays.toString(stylePropertyElements));
elem.setAttribute(stylePropertyElements[0].trim(), SVG_NAMESPACE, stylePropertyElements[1].trim());
}
}
}
styleManager.applyStylesTo(elem);
for (IXMLElement child : elem.getChildren()) {
flattenStyles(child);
}
}
}
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
Nullable
private Figure readElement(IXMLElement elem)
throws IOException {
if (DEBUG) {
System.out.println("SVGInputFormat.readElement " + elem.getName() + " line:" + elem.getLineNr());
}
Figure f = null;
if (elem.getNamespace() == null
|| elem.getNamespace().equals(SVG_NAMESPACE)) {
String name = elem.getName();
if (name == null) {
if (DEBUG) {
System.err.println("SVGInputFormat warning: skipping nameless element at line " + elem.getLineNr());
}
} else if (name.equals("a")) {
f = readAElement(elem);
} else if (name.equals("circle")) {
f = readCircleElement(elem);
} else if (name.equals("defs")) {
readDefsElement(elem);
f = null;
} else if (name.equals("ellipse")) {
f = readEllipseElement(elem);
} else if (name.equals("g")) {
f = readGElement(elem);
} else if (name.equals("image")) {
f = readImageElement(elem);
} else if (name.equals("line")) {
f = readLineElement(elem);
} else if (name.equals("linearGradient")) {
readLinearGradientElement(elem);
f = null;
} else if (name.equals("path")) {
f = readPathElement(elem);
} else if (name.equals("polygon")) {
f = readPolygonElement(elem);
} else if (name.equals("polyline")) {
f = readPolylineElement(elem);
} else if (name.equals("radialGradient")) {
readRadialGradientElement(elem);
f = null;
} else if (name.equals("rect")) {
f = readRectElement(elem);
} else if (name.equals("solidColor")) {
readSolidColorElement(elem);
f = null;
} else if (name.equals("svg")) {
f = readSVGElement(elem);
//f = readGElement(elem);
} else if (name.equals("switch")) {
f = readSwitchElement(elem);
} else if (name.equals("text")) {
f = readTextElement(elem);
} else if (name.equals("textArea")) {
f = readTextAreaElement(elem);
} else if (name.equals("title")) {
//FIXME - Implement reading of title element
//f = readTitleElement(elem);
} else if (name.equals("use")) {
f = readUseElement(elem);
} else if (name.equals("style")) {
// Nothing to do, style elements have been already
// processed in method flattenStyles
} else {
if (DEBUG) {
System.out.println("SVGInputFormat not implemented for <" + name + ">");
}
}
}
if (f instanceof SVGFigure) {
if (((SVGFigure) f).isEmpty()) {
// if (DEBUG) System.out.println("Empty figure "+f);
return null;
}
} else if (f != null) {
if (DEBUG) {
System.out.println("SVGInputFormat warning: not an SVGFigure " + f);
}
}
return f;
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
private void readDefsElement(IXMLElement elem)
throws IOException {
for (IXMLElement child : elem.getChildren()) {
Figure childFigure = readElement(child);
}
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
private Figure readGElement(IXMLElement elem)
throws IOException {
HashMap<AttributeKey, Object> a = new HashMap<AttributeKey, Object>();
readCoreAttributes(elem, a);
readOpacityAttribute(elem, a);
CompositeFigure g = factory.createG(a);
for (IXMLElement child : elem.getChildren()) {
Figure childFigure = readElement(child);
// skip invisible elements
if (readAttribute(child, "visibility", "visible").equals("visible")
&& !readAttribute(child, "display", "inline").equals("none")) {
if (childFigure != null) {
g.basicAdd(childFigure);
}
}
}
readTransformAttribute(elem, a);
if (TRANSFORM.get(a) != null) {
g.transform(TRANSFORM.get(a));
}
return g;
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
private Figure readAElement(IXMLElement elem)
throws IOException {
HashMap<AttributeKey, Object> a = new HashMap<AttributeKey, Object>();
readCoreAttributes(elem, a);
CompositeFigure g = factory.createG(a);
String href = readAttribute(elem, "xlink:href", null);
if (href == null) {
href = readAttribute(elem, "href", null);
}
String target = readAttribute(elem, "target", null);
if (DEBUG) {
System.out.println("SVGInputFormat.readAElement href=" + href);
}
for (IXMLElement child : elem.getChildren()) {
Figure childFigure = readElement(child);
// skip invisible elements
if (readAttribute(child, "visibility", "visible").equals("visible")
&& !readAttribute(child, "display", "inline").equals("none")) {
if (childFigure != null) {
g.basicAdd(childFigure);
}
}
if (childFigure != null) {
childFigure.set(LINK, href);
childFigure.set(LINK_TARGET, target);
} else {
if (DEBUG) {
System.out.println("SVGInputFormat <a> has no child figure");
}
}
}
return (g.getChildCount() == 1) ? g.getChild(0) : g;
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
Nullable
private Figure readSVGElement(IXMLElement elem)
throws IOException {
// Establish a new viewport
Viewport viewport = new Viewport();
String widthValue = readAttribute(elem, "width", "100%");
String heightValue = readAttribute(elem, "height", "100%");
viewport.width = toWidth(elem, widthValue);
viewport.height = toHeight(elem, heightValue);
if (readAttribute(elem, "viewBox", "none").equals("none")) {
viewport.viewBox.width = viewport.width;
viewport.viewBox.height = viewport.height;
} else {
String[] viewBoxValues = toWSOrCommaSeparatedArray(readAttribute(elem, "viewBox", "none"));
viewport.viewBox.x = toNumber(elem, viewBoxValues[0]);
viewport.viewBox.y = toNumber(elem, viewBoxValues[1]);
viewport.viewBox.width = toNumber(elem, viewBoxValues[2]);
viewport.viewBox.height = toNumber(elem, viewBoxValues[3]);
// FIXME - Calculate percentages
if (widthValue.indexOf('%') > 0) {
viewport.width = viewport.viewBox.width;
}
if (heightValue.indexOf('%') > 0) {
viewport.height = viewport.viewBox.height;
}
}
if (viewportStack.size() == 1) {
// We always preserve the aspect ratio for to the topmost SVG element.
// This is not compliant, but looks much better.
viewport.isPreserveAspectRatio = true;
} else {
viewport.isPreserveAspectRatio = !readAttribute(elem, "preserveAspectRatio", "none").equals("none");
}
viewport.widthPercentFactor = viewport.viewBox.width / 100d;
viewport.heightPercentFactor = viewport.viewBox.height / 100d;
viewport.numberFactor = Math.min(
viewport.width / viewport.viewBox.width,
viewport.height / viewport.viewBox.height);
AffineTransform viewBoxTransform = new AffineTransform();
viewBoxTransform.translate(
-viewport.viewBox.x * viewport.width / viewport.viewBox.width,
-viewport.viewBox.y * viewport.height / viewport.viewBox.height);
if (viewport.isPreserveAspectRatio) {
double factor = Math.min(
viewport.width / viewport.viewBox.width,
viewport.height / viewport.viewBox.height);
viewBoxTransform.scale(factor, factor);
} else {
viewBoxTransform.scale(
viewport.width / viewport.viewBox.width,
viewport.height / viewport.viewBox.height);
}
viewportStack.push(viewport);
readViewportAttributes(elem, viewportStack.firstElement().attributes);
// Read the figures
for (IXMLElement child : elem.getChildren()) {
Figure childFigure = readElement(child);
// skip invisible elements
if (readAttribute(child, "visibility", "visible").equals("visible")
&& !readAttribute(child, "display", "inline").equals("none")) {
if (childFigure != null) {
childFigure.transform(viewBoxTransform);
figures.add(childFigure);
}
}
}
viewportStack.pop();
return null;
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
private Figure readRectElement(IXMLElement elem)
throws IOException {
HashMap<AttributeKey, Object> a = new HashMap<AttributeKey, Object>();
readCoreAttributes(elem, a);
readTransformAttribute(elem, a);
readOpacityAttribute(elem, a);
readShapeAttributes(elem, a);
double x = toNumber(elem, readAttribute(elem, "x", "0"));
double y = toNumber(elem, readAttribute(elem, "y", "0"));
double w = toWidth(elem, readAttribute(elem, "width", "0"));
double h = toHeight(elem, readAttribute(elem, "height", "0"));
String rxValue = readAttribute(elem, "rx", "none");
String ryValue = readAttribute(elem, "ry", "none");
if (rxValue.equals("none")) {
rxValue = ryValue;
}
if (ryValue.equals("none")) {
ryValue = rxValue;
}
double rx = toNumber(elem, rxValue.equals("none") ? "0" : rxValue);
double ry = toNumber(elem, ryValue.equals("none") ? "0" : ryValue);
Figure figure = factory.createRect(x, y, w, h, rx, ry, a);
elementObjects.put(elem, figure);
return figure;
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
private Figure readCircleElement(IXMLElement elem)
throws IOException {
HashMap<AttributeKey, Object> a = new HashMap<AttributeKey, Object>();
readCoreAttributes(elem, a);
readTransformAttribute(elem, a);
readOpacityAttribute(elem, a);
readShapeAttributes(elem, a);
double cx = toWidth(elem, readAttribute(elem, "cx", "0"));
double cy = toHeight(elem, readAttribute(elem, "cy", "0"));
double r = toWidth(elem, readAttribute(elem, "r", "0"));
Figure figure = factory.createCircle(cx, cy, r, a);
elementObjects.put(elem, figure);
return figure;
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
private Figure readEllipseElement(IXMLElement elem)
throws IOException {
HashMap<AttributeKey, Object> a = new HashMap<AttributeKey, Object>();
readCoreAttributes(elem, a);
readTransformAttribute(elem, a);
readOpacityAttribute(elem, a);
readShapeAttributes(elem, a);
double cx = toWidth(elem, readAttribute(elem, "cx", "0"));
double cy = toHeight(elem, readAttribute(elem, "cy", "0"));
double rx = toWidth(elem, readAttribute(elem, "rx", "0"));
double ry = toHeight(elem, readAttribute(elem, "ry", "0"));
Figure figure = factory.createEllipse(cx, cy, rx, ry, a);
elementObjects.put(elem, figure);
return figure;
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
private Figure readImageElement(IXMLElement elem)
throws IOException {
HashMap<AttributeKey, Object> a = new HashMap<AttributeKey, Object>();
readCoreAttributes(elem, a);
readTransformAttribute(elem, a);
readOpacityAttribute(elem, a);
double x = toNumber(elem, readAttribute(elem, "x", "0"));
double y = toNumber(elem, readAttribute(elem, "y", "0"));
double w = toWidth(elem, readAttribute(elem, "width", "0"));
double h = toHeight(elem, readAttribute(elem, "height", "0"));
String href = readAttribute(elem, "xlink:href", null);
if (href == null) {
href = readAttribute(elem, "href", null);
}
byte[] imageData = null;
if (href != null) {
if (href.startsWith("data:")) {
int semicolonPos = href.indexOf(';');
if (semicolonPos != -1) {
if (href.indexOf(";base64,") == semicolonPos) {
imageData = Base64.decode(href.substring(semicolonPos + 8));
} else {
throw new IOException("Unsupported encoding in data href in image element:" + href);
}
} else {
throw new IOException("Unsupported data href in image element:" + href);
}
} else {
URL imageUrl = new URL(url, href);
// Check whether the imageURL is an SVG image.
// Load it as a group.
if (imageUrl.getFile().endsWith("svg")) {
SVGInputFormat svgImage = new SVGInputFormat(factory);
Drawing svgDrawing = new DefaultDrawing();
svgImage.read(imageUrl, svgDrawing, true);
CompositeFigure svgImageGroup = factory.createG(a);
for (Figure f : svgDrawing.getChildren()) {
svgImageGroup.add(f);
}
svgImageGroup.setBounds(new Point2D.Double(x, y), new Point2D.Double(x + w, y + h));
return svgImageGroup;
}
// Read the image data from the URL into a byte array
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] buf = new byte[512];
int len = 0;
try {
InputStream in = imageUrl.openStream();
try {
while ((len = in.read(buf)) > 0) {
bout.write(buf, 0, len);
}
imageData = bout.toByteArray();
} finally {
in.close();
}
} catch (FileNotFoundException e) {
// Use empty image
}
}
}
// Create a buffered image from the image data
BufferedImage bufferedImage = null;
if (imageData != null) {
try {
bufferedImage = ImageIO.read(new ByteArrayInputStream(imageData));
} catch (IIOException e) {
System.err.println("SVGInputFormat warning: skipped unsupported image format.");
e.printStackTrace();
}
}
// Delete the image data in case of failure
if (bufferedImage == null) {
imageData = null;
//if (DEBUG) System.out.println("FAILED:"+imageUrl);
}
// Create a figure from the image data and the buffered image.
Figure figure = factory.createImage(x, y, w, h, imageData, bufferedImage, a);
elementObjects.put(elem, figure);
return figure;
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
private Figure readLineElement(IXMLElement elem)
throws IOException {
HashMap<AttributeKey, Object> a = new HashMap<AttributeKey, Object>();
readCoreAttributes(elem, a);
readTransformAttribute(elem, a);
readOpacityAttribute(elem, a);
readLineAttributes(elem, a);
// Because 'line' elements are single lines and thus are geometrically
// one-dimensional, they have no interior; thus, 'line' elements are
// never filled (see the 'fill' property).
if (FILL_COLOR.get(a) != null && STROKE_COLOR.get(a) == null) {
STROKE_COLOR.put(a, FILL_COLOR.get(a));
}
if (FILL_GRADIENT.get(a) != null && STROKE_GRADIENT.get(a) == null) {
STROKE_GRADIENT.put(a, FILL_GRADIENT.get(a));
}
FILL_COLOR.put(a, null);
FILL_GRADIENT.put(a, null);
double x1 = toNumber(elem, readAttribute(elem, "x1", "0"));
double y1 = toNumber(elem, readAttribute(elem, "y1", "0"));
double x2 = toNumber(elem, readAttribute(elem, "x2", "0"));
double y2 = toNumber(elem, readAttribute(elem, "y2", "0"));
Figure figure = factory.createLine(x1, y1, x2, y2, a);
elementObjects.put(elem, figure);
return figure;
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
private Figure readPolylineElement(IXMLElement elem)
throws IOException {
HashMap<AttributeKey, Object> a = new HashMap<AttributeKey, Object>();
readCoreAttributes(elem, a);
readTransformAttribute(elem, a);
readOpacityAttribute(elem, a);
readLineAttributes(elem, a);
Point2D.Double[] points = toPoints(elem, readAttribute(elem, "points", ""));
Figure figure = factory.createPolyline(points, a);
elementObjects.put(elem, figure);
return figure;
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
private Figure readPolygonElement(IXMLElement elem)
throws IOException {
HashMap<AttributeKey, Object> a = new HashMap<AttributeKey, Object>();
readCoreAttributes(elem, a);
readTransformAttribute(elem, a);
readOpacityAttribute(elem, a);
readShapeAttributes(elem, a);
Point2D.Double[] points = toPoints(elem, readAttribute(elem, "points", ""));
Figure figure = factory.createPolygon(points, a);
elementObjects.put(elem, figure);
return figure;
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
private Figure readPathElement(IXMLElement elem)
throws IOException {
HashMap<AttributeKey, Object> a = new HashMap<AttributeKey, Object>();
readCoreAttributes(elem, a);
readTransformAttribute(elem, a);
readOpacityAttribute(elem, a);
readShapeAttributes(elem, a);
BezierPath[] beziers = toPath(elem, readAttribute(elem, "d", ""));
Figure figure = factory.createPath(beziers, a);
elementObjects.put(elem, figure);
return figure;
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
private Figure readTextElement(IXMLElement elem)
throws IOException {
HashMap<AttributeKey, Object> a = new HashMap<AttributeKey, Object>();
readCoreAttributes(elem, a);
readTransformAttribute(elem, a);
readOpacityAttribute(elem, a);
readShapeAttributes(elem, a);
readFontAttributes(elem, a);
readTextAttributes(elem, a);
String[] xStr = toCommaSeparatedArray(readAttribute(elem, "x", "0"));
String[] yStr = toCommaSeparatedArray(readAttribute(elem, "y", "0"));
Point2D.Double[] coordinates = new Point2D.Double[Math.max(xStr.length, yStr.length)];
double lastX = 0;
double lastY = 0;
for (int i = 0; i < coordinates.length; i++) {
if (xStr.length > i) {
try {
lastX = toNumber(elem, xStr[i]);
} catch (NumberFormatException ex) {
}
}
if (yStr.length > i) {
try {
lastY = toNumber(elem, yStr[i]);
} catch (NumberFormatException ex) {
}
}
coordinates[i] = new Point2D.Double(lastX, lastY);
}
String[] rotateStr = toCommaSeparatedArray(readAttribute(elem, "rotate", ""));
double[] rotate = new double[rotateStr.length];
for (int i = 0; i < rotateStr.length; i++) {
try {
rotate[i] = toDouble(elem, rotateStr[i]);
} catch (NumberFormatException ex) {
rotate[i] = 0;
}
}
DefaultStyledDocument doc = new DefaultStyledDocument();
try {
if (elem.getContent() != null) {
doc.insertString(0, toText(elem, elem.getContent()), null);
} else {
for (IXMLElement node : elem.getChildren()) {
if (node.getName() == null) {
doc.insertString(0, toText(elem, node.getContent()), null);
} else if (node.getName().equals("tspan")) {
readTSpanElement((IXMLElement) node, doc);
} else {
if (DEBUG) {
System.out.println("SVGInputFormat unsupported text node <" + node.getName() + ">");
}
}
}
}
} catch (BadLocationException e) {
InternalError ex = new InternalError(e.getMessage());
ex.initCause(e);
throw ex;
}
Figure figure = factory.createText(coordinates, rotate, doc, a);
elementObjects.put(elem, figure);
return figure;
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
private Figure readTextAreaElement(IXMLElement elem)
throws IOException {
HashMap<AttributeKey, Object> a = new HashMap<AttributeKey, Object>();
readCoreAttributes(elem, a);
readTransformAttribute(elem, a);
readOpacityAttribute(elem, a);
readShapeAttributes(elem, a);
readFontAttributes(elem, a);
readTextAttributes(elem, a);
readTextFlowAttributes(elem, a);
double x = toNumber(elem, readAttribute(elem, "x", "0"));
double y = toNumber(elem, readAttribute(elem, "y", "0"));
// XXX - Handle "auto" width and height
double w = toWidth(elem, readAttribute(elem, "width", "0"));
double h = toHeight(elem, readAttribute(elem, "height", "0"));
DefaultStyledDocument doc = new DefaultStyledDocument();
try {
if (elem.getContent() != null) {
doc.insertString(0, toText(elem, elem.getContent()), null);
} else {
for (IXMLElement node : elem.getChildren()) {
if (node.getName() == null) {
doc.insertString(doc.getLength(), toText(elem, node.getContent()), null);
} else if (node.getName().equals("tbreak")) {
doc.insertString(doc.getLength(), "\n", null);
} else if (node.getName().equals("tspan")) {
readTSpanElement((IXMLElement) node, doc);
} else {
if (DEBUG) {
System.out.println("SVGInputFormat unknown text node " + node.getName());
}
}
}
}
} catch (BadLocationException e) {
InternalError ex = new InternalError(e.getMessage());
ex.initCause(e);
throw ex;
}
Figure figure = factory.createTextArea(x, y, w, h, doc, a);
elementObjects.put(elem, figure);
return figure;
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
private void readTSpanElement(IXMLElement elem, DefaultStyledDocument doc)
throws IOException {
try {
if (elem.getContent() != null) {
doc.insertString(doc.getLength(), toText(elem, elem.getContent()), null);
} else {
for (IXMLElement node : elem.getChildren()) {
if (node.getName() != null && node.getName().equals("tspan")) {
readTSpanElement((IXMLElement) node, doc);
} else {
if (DEBUG) {
System.out.println("SVGInputFormat unknown text node " + node.getName());
}
}
}
}
} catch (BadLocationException e) {
InternalError ex = new InternalError(e.getMessage());
ex.initCause(e);
throw ex;
}
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
Nullable
private Figure readSwitchElement(IXMLElement elem)
throws IOException {
for (IXMLElement child : elem.getChildren()) {
String[] requiredFeatures = toWSOrCommaSeparatedArray(readAttribute(child, "requiredFeatures", ""));
String[] requiredExtensions = toWSOrCommaSeparatedArray(readAttribute(child, "requiredExtensions", ""));
String[] systemLanguage = toWSOrCommaSeparatedArray(readAttribute(child, "systemLanguage", ""));
String[] requiredFormats = toWSOrCommaSeparatedArray(readAttribute(child, "requiredFormats", ""));
String[] requiredFonts = toWSOrCommaSeparatedArray(readAttribute(child, "requiredFonts", ""));
boolean isMatch;
isMatch = supportedFeatures.containsAll(Arrays.asList(requiredFeatures))
&& requiredExtensions.length == 0
&& requiredFormats.length == 0
&& requiredFonts.length == 0;
if (isMatch && systemLanguage.length > 0) {
isMatch = false;
Locale locale = LocaleUtil.getDefault();
for (String lng : systemLanguage) {
int p = lng.indexOf('-');
if (p == -1) {
if (locale.getLanguage().equals(lng)) {
isMatch = true;
break;
}
} else {
if (locale.getLanguage().equals(lng.substring(0, p))
&& locale.getCountry().toLowerCase().equals(lng.substring(p + 1))) {
isMatch = true;
break;
}
}
}
}
if (isMatch) {
Figure figure = readElement(child);
if (readAttribute(child, "visibility", "visible").equals("visible")
&& !readAttribute(child, "display", "inline").equals("none")) {
return figure;
} else {
return null;
}
}
}
return null;
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
private double readInheritFontSizeAttribute(IXMLElement elem, String attributeName, String defaultValue)
throws IOException {
String value = null;
if (elem.hasAttribute(attributeName, SVG_NAMESPACE)) {
value = elem.getAttribute(attributeName, SVG_NAMESPACE, null);
} else if (elem.hasAttribute(attributeName)) {
value = elem.getAttribute(attributeName, null);
} else if (elem.getParent() != null
&& (elem.getParent().getNamespace() == null
|| elem.getParent().getNamespace().equals(SVG_NAMESPACE))) {
return readInheritFontSizeAttribute(elem.getParent(), attributeName, defaultValue);
} else {
value = defaultValue;
}
if (value.equals("inherit")) {
return readInheritFontSizeAttribute(elem.getParent(), attributeName, defaultValue);
} else if (SVG_ABSOLUTE_FONT_SIZES.containsKey(value)) {
return SVG_ABSOLUTE_FONT_SIZES.get(value);
} else if (SVG_RELATIVE_FONT_SIZES.containsKey(value)) {
return SVG_RELATIVE_FONT_SIZES.get(value) * readInheritFontSizeAttribute(elem.getParent(), attributeName, defaultValue);
} else if (value.endsWith("%")) {
double factor = Double.valueOf(value.substring(0, value.length() - 1));
return factor * readInheritFontSizeAttribute(elem.getParent(), attributeName, defaultValue);
} else {
//return toScaledNumber(elem, value);
return toNumber(elem, value);
}
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
private double toWidth(IXMLElement elem, String str) throws IOException {
// XXX - Compute xPercentFactor from viewport
return toLength(elem, str,
viewportStack.peek().widthPercentFactor);
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
private double toHeight(IXMLElement elem, String str) throws IOException {
// XXX - Compute yPercentFactor from viewport
return toLength(elem, str,
viewportStack.peek().heightPercentFactor);
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
private double toNumber(IXMLElement elem, String str) throws IOException {
return toLength(elem, str, viewportStack.peek().numberFactor);
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
private double toLength(IXMLElement elem, String str, double percentFactor) throws IOException {
double scaleFactor = 1d;
if (str == null || str.length() == 0 || str.equals("none")) {
return 0d;
}
if (str.endsWith("%")) {
str = str.substring(0, str.length() - 1);
scaleFactor = percentFactor;
} else if (str.endsWith("px")) {
str = str.substring(0, str.length() - 2);
} else if (str.endsWith("pt")) {
str = str.substring(0, str.length() - 2);
scaleFactor = 1.25;
} else if (str.endsWith("pc")) {
str = str.substring(0, str.length() - 2);
scaleFactor = 15;
} else if (str.endsWith("mm")) {
str = str.substring(0, str.length() - 2);
scaleFactor = 3.543307;
} else if (str.endsWith("cm")) {
str = str.substring(0, str.length() - 2);
scaleFactor = 35.43307;
} else if (str.endsWith("in")) {
str = str.substring(0, str.length() - 2);
scaleFactor = 90;
} else if (str.endsWith("em")) {
str = str.substring(0, str.length() - 2);
// XXX - This doesn't work
scaleFactor = toLength(elem, readAttribute(elem, "font-size", "0"), percentFactor);
} else {
scaleFactor = 1d;
}
return Double.parseDouble(str) * scaleFactor;
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
public static String[] toCommaSeparatedArray(String str) throws IOException {
return str.split("\\s*,\\s*");
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
public static String[] toWSOrCommaSeparatedArray(String str) throws IOException {
String[] result = str.split("(\\s*,\\s*|\\s+)");
if (result.length == 1 && result[0].equals("")) {
return new String[0];
} else {
return result;
}
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
public static String[] toQuotedAndCommaSeparatedArray(String str) throws IOException {
LinkedList<String> values = new LinkedList<String>();
StreamTokenizer tt = new StreamTokenizer(new StringReader(str));
tt.wordChars('a', 'z');
tt.wordChars('A', 'Z');
tt.wordChars(128 + 32, 255);
tt.whitespaceChars(0, ' ');
tt.quoteChar('"');
tt.quoteChar('\'');
while (tt.nextToken() != StreamTokenizer.TT_EOF) {
switch (tt.ttype) {
case StreamTokenizer.TT_WORD:
case '"':
case '\'':
values.add(tt.sval);
break;
}
}
return values.toArray(new String[values.size()]);
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
private Point2D.Double[] toPoints(IXMLElement elem, String str) throws IOException {
StringTokenizer tt = new StringTokenizer(str, " ,");
Point2D.Double[] points = new Point2D.Double[tt.countTokens() / 2];
for (int i = 0; i < points.length; i++) {
points[i] = new Point2D.Double(
toNumber(elem, tt.nextToken()),
toNumber(elem, tt.nextToken()));
}
return points;
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
private BezierPath[] toPath(IXMLElement elem, String str) throws IOException {
LinkedList<BezierPath> paths = new LinkedList<BezierPath>();
BezierPath path = null;
Point2D.Double p = new Point2D.Double();
Point2D.Double c1 = new Point2D.Double();
Point2D.Double c2 = new Point2D.Double();
StreamPosTokenizer tt;
if (toPathTokenizer == null) {
tt = new StreamPosTokenizer(new StringReader(str));
tt.resetSyntax();
tt.parseNumbers();
tt.parseExponents();
tt.parsePlusAsNumber();
tt.whitespaceChars(0, ' ');
tt.whitespaceChars(',', ',');
toPathTokenizer = tt;
} else {
tt = toPathTokenizer;
tt.setReader(new StringReader(str));
}
char nextCommand = 'M';
char command = 'M';
Commands:
while (tt.nextToken() != StreamPosTokenizer.TT_EOF) {
if (tt.ttype > 0) {
command = (char) tt.ttype;
} else {
command = nextCommand;
tt.pushBack();
}
BezierPath.Node node;
switch (command) {
case 'M':
// absolute-moveto x y
if (path != null) {
paths.add(path);
}
path = new BezierPath();
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("x coordinate missing for 'M' at position " + tt.getStartPosition() + " in " + str);
}
p.x = tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("y coordinate missing for 'M' at position " + tt.getStartPosition() + " in " + str);
}
p.y = tt.nval;
path.moveTo(p.x, p.y);
nextCommand = 'L';
break;
case 'm':
// relative-moveto dx dy
if (path != null) {
paths.add(path);
}
path = new BezierPath();
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dx coordinate missing for 'm' at position " + tt.getStartPosition() + " in " + str);
}
p.x += tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dy coordinate missing for 'm' at position " + tt.getStartPosition() + " in " + str);
}
p.y += tt.nval;
path.moveTo(p.x, p.y);
nextCommand = 'l';
break;
case 'Z':
case 'z':
// close path
p.x = path.get(0).x[0];
p.y = path.get(0).y[0];
// If the last point and the first point are the same, we
// can merge them
if (path.size() > 1) {
BezierPath.Node first = path.get(0);
BezierPath.Node last = path.get(path.size() - 1);
if (first.x[0] == last.x[0]
&& first.y[0] == last.y[0]) {
if ((last.mask & BezierPath.C1_MASK) != 0) {
first.mask |= BezierPath.C1_MASK;
first.x[1] = last.x[1];
first.y[1] = last.y[1];
}
path.remove(path.size() - 1);
}
}
path.setClosed(true);
break;
case 'L':
// absolute-lineto x y
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("x coordinate missing for 'L' at position " + tt.getStartPosition() + " in " + str);
}
p.x = tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("y coordinate missing for 'L' at position " + tt.getStartPosition() + " in " + str);
}
p.y = tt.nval;
path.lineTo(p.x, p.y);
nextCommand = 'L';
break;
case 'l':
// relative-lineto dx dy
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dx coordinate missing for 'l' at position " + tt.getStartPosition() + " in " + str);
}
p.x += tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dy coordinate missing for 'l' at position " + tt.getStartPosition() + " in " + str);
}
p.y += tt.nval;
path.lineTo(p.x, p.y);
nextCommand = 'l';
break;
case 'H':
// absolute-horizontal-lineto x
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("x coordinate missing for 'H' at position " + tt.getStartPosition() + " in " + str);
}
p.x = tt.nval;
path.lineTo(p.x, p.y);
nextCommand = 'H';
break;
case 'h':
// relative-horizontal-lineto dx
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dx coordinate missing for 'h' at position " + tt.getStartPosition() + " in " + str);
}
p.x += tt.nval;
path.lineTo(p.x, p.y);
nextCommand = 'h';
break;
case 'V':
// absolute-vertical-lineto y
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("y coordinate missing for 'V' at position " + tt.getStartPosition() + " in " + str);
}
p.y = tt.nval;
path.lineTo(p.x, p.y);
nextCommand = 'V';
break;
case 'v':
// relative-vertical-lineto dy
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dy coordinate missing for 'v' at position " + tt.getStartPosition() + " in " + str);
}
p.y += tt.nval;
path.lineTo(p.x, p.y);
nextCommand = 'v';
break;
case 'C':
// absolute-curveto x1 y1 x2 y2 x y
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("x1 coordinate missing for 'C' at position " + tt.getStartPosition() + " in " + str);
}
c1.x = tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("y1 coordinate missing for 'C' at position " + tt.getStartPosition() + " in " + str);
}
c1.y = tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("x2 coordinate missing for 'C' at position " + tt.getStartPosition() + " in " + str);
}
c2.x = tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("y2 coordinate missing for 'C' at position " + tt.getStartPosition() + " in " + str);
}
c2.y = tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("x coordinate missing for 'C' at position " + tt.getStartPosition() + " in " + str);
}
p.x = tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("y coordinate missing for 'C' at position " + tt.getStartPosition() + " in " + str);
}
p.y = tt.nval;
path.curveTo(c1.x, c1.y, c2.x, c2.y, p.x, p.y);
nextCommand = 'C';
break;
case 'c':
// relative-curveto dx1 dy1 dx2 dy2 dx dy
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dx1 coordinate missing for 'c' at position " + tt.getStartPosition() + " in " + str);
}
c1.x = p.x + tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dy1 coordinate missing for 'c' at position " + tt.getStartPosition() + " in " + str);
}
c1.y = p.y + tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dx2 coordinate missing for 'c' at position " + tt.getStartPosition() + " in " + str);
}
c2.x = p.x + tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dy2 coordinate missing for 'c' at position " + tt.getStartPosition() + " in " + str);
}
c2.y = p.y + tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dx coordinate missing for 'c' at position " + tt.getStartPosition() + " in " + str);
}
p.x += tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dy coordinate missing for 'c' at position " + tt.getStartPosition() + " in " + str);
}
p.y += tt.nval;
path.curveTo(c1.x, c1.y, c2.x, c2.y, p.x, p.y);
nextCommand = 'c';
break;
case 'S':
// absolute-shorthand-curveto x2 y2 x y
node = path.get(path.size() - 1);
c1.x = node.x[0] * 2d - node.x[1];
c1.y = node.y[0] * 2d - node.y[1];
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("x2 coordinate missing for 'S' at position " + tt.getStartPosition() + " in " + str);
}
c2.x = tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("y2 coordinate missing for 'S' at position " + tt.getStartPosition() + " in " + str);
}
c2.y = tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("x coordinate missing for 'S' at position " + tt.getStartPosition() + " in " + str);
}
p.x = tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("y coordinate missing for 'S' at position " + tt.getStartPosition() + " in " + str);
}
p.y = tt.nval;
path.curveTo(c1.x, c1.y, c2.x, c2.y, p.x, p.y);
nextCommand = 'S';
break;
case 's':
// relative-shorthand-curveto dx2 dy2 dx dy
node = path.get(path.size() - 1);
c1.x = node.x[0] * 2d - node.x[1];
c1.y = node.y[0] * 2d - node.y[1];
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dx2 coordinate missing for 's' at position " + tt.getStartPosition() + " in " + str);
}
c2.x = p.x + tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dy2 coordinate missing for 's' at position " + tt.getStartPosition() + " in " + str);
}
c2.y = p.y + tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dx coordinate missing for 's' at position " + tt.getStartPosition() + " in " + str);
}
p.x += tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dy coordinate missing for 's' at position " + tt.getStartPosition() + " in " + str);
}
p.y += tt.nval;
path.curveTo(c1.x, c1.y, c2.x, c2.y, p.x, p.y);
nextCommand = 's';
break;
case 'Q':
// absolute-quadto x1 y1 x y
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("x1 coordinate missing for 'Q' at position " + tt.getStartPosition() + " in " + str);
}
c1.x = tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("y1 coordinate missing for 'Q' at position " + tt.getStartPosition() + " in " + str);
}
c1.y = tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("x coordinate missing for 'Q' at position " + tt.getStartPosition() + " in " + str);
}
p.x = tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("y coordinate missing for 'Q' at position " + tt.getStartPosition() + " in " + str);
}
p.y = tt.nval;
path.quadTo(c1.x, c1.y, p.x, p.y);
nextCommand = 'Q';
break;
case 'q':
// relative-quadto dx1 dy1 dx dy
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dx1 coordinate missing for 'q' at position " + tt.getStartPosition() + " in " + str);
}
c1.x = p.x + tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dy1 coordinate missing for 'q' at position " + tt.getStartPosition() + " in " + str);
}
c1.y = p.y + tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dx coordinate missing for 'q' at position " + tt.getStartPosition() + " in " + str);
}
p.x += tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dy coordinate missing for 'q' at position " + tt.getStartPosition() + " in " + str);
}
p.y += tt.nval;
path.quadTo(c1.x, c1.y, p.x, p.y);
nextCommand = 'q';
break;
case 'T':
// absolute-shorthand-quadto x y
node = path.get(path.size() - 1);
c1.x = node.x[0] * 2d - node.x[1];
c1.y = node.y[0] * 2d - node.y[1];
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("x coordinate missing for 'T' at position " + tt.getStartPosition() + " in " + str);
}
p.x = tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("y coordinate missing for 'T' at position " + tt.getStartPosition() + " in " + str);
}
p.y = tt.nval;
path.quadTo(c1.x, c1.y, p.x, p.y);
nextCommand = 'T';
break;
case 't':
// relative-shorthand-quadto dx dy
node = path.get(path.size() - 1);
c1.x = node.x[0] * 2d - node.x[1];
c1.y = node.y[0] * 2d - node.y[1];
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dx coordinate missing for 't' at position " + tt.getStartPosition() + " in " + str);
}
p.x += tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dy coordinate missing for 't' at position " + tt.getStartPosition() + " in " + str);
}
p.y += tt.nval;
path.quadTo(c1.x, c1.y, p.x, p.y);
nextCommand = 's';
break;
case 'A': {
// absolute-elliptical-arc rx ry x-axis-rotation large-arc-flag sweep-flag x y
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("rx coordinate missing for 'A' at position " + tt.getStartPosition() + " in " + str);
}
// If rX or rY have negative signs, these are dropped;
// the absolute value is used instead.
double rx = tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("ry coordinate missing for 'A' at position " + tt.getStartPosition() + " in " + str);
}
double ry = tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("x-axis-rotation missing for 'A' at position " + tt.getStartPosition() + " in " + str);
}
double xAxisRotation = tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("large-arc-flag missing for 'A' at position " + tt.getStartPosition() + " in " + str);
}
boolean largeArcFlag = tt.nval != 0;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("sweep-flag missing for 'A' at position " + tt.getStartPosition() + " in " + str);
}
boolean sweepFlag = tt.nval != 0;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("x coordinate missing for 'A' at position " + tt.getStartPosition() + " in " + str);
}
p.x = tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("y coordinate missing for 'A' at position " + tt.getStartPosition() + " in " + str);
}
p.y = tt.nval;
path.arcTo(rx, ry, xAxisRotation, largeArcFlag, sweepFlag, p.x, p.y);
nextCommand = 'A';
break;
}
case 'a': {
// absolute-elliptical-arc rx ry x-axis-rotation large-arc-flag sweep-flag x y
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("rx coordinate missing for 'A' at position " + tt.getStartPosition() + " in " + str);
}
// If rX or rY have negative signs, these are dropped;
// the absolute value is used instead.
double rx = tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("ry coordinate missing for 'A' at position " + tt.getStartPosition() + " in " + str);
}
double ry = tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("x-axis-rotation missing for 'A' at position " + tt.getStartPosition() + " in " + str);
}
double xAxisRotation = tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("large-arc-flag missing for 'A' at position " + tt.getStartPosition() + " in " + str);
}
boolean largeArcFlag = tt.nval != 0;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("sweep-flag missing for 'A' at position " + tt.getStartPosition() + " in " + str);
}
boolean sweepFlag = tt.nval != 0;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("x coordinate missing for 'A' at position " + tt.getStartPosition() + " in " + str);
}
p.x += tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("y coordinate missing for 'A' at position " + tt.getStartPosition() + " in " + str);
}
p.y += tt.nval;
path.arcTo(rx, ry, xAxisRotation, largeArcFlag, sweepFlag, p.x, p.y);
nextCommand = 'a';
break;
}
default:
if (DEBUG) {
System.out.println("SVGInputFormat.toPath aborting after illegal path command: " + command + " found in path " + str);
}
break Commands;
//throw new IOException("Illegal command: "+command);
}
}
if (path != null) {
paths.add(path);
}
return paths.toArray(new BezierPath[paths.size()]);
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
private void readCoreAttributes(IXMLElement elem, HashMap<AttributeKey, Object> a)
throws IOException {
// read "id" or "xml:id"
//identifiedElements.putx(elem.get("id"), elem);
//identifiedElements.putx(elem.get("xml:id"), elem);
// XXX - Add
// xml:base
// xml:lang
// xml:space
// class
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
private void readOpacityAttribute(IXMLElement elem, Map<AttributeKey, Object> a)
throws IOException {
//'opacity'
//Value: <opacity-value> | inherit
//Initial: 1
//Applies to: 'image' element
//Inherited: no
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
//<opacity-value>
//The uniform opacity setting must be applied across an entire object.
//Any values outside the range 0.0 (fully transparent) to 1.0
//(fully opaque) shall be clamped to this range.
//(See Clamping values which are restricted to a particular range.)
double value = toDouble(elem, readAttribute(elem, "opacity", "1"), 1, 0, 1);
OPACITY.put(a, value);
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
private void readTextAttributes(IXMLElement elem, Map<AttributeKey, Object> a)
throws IOException {
Object value;
//'text-anchor'
//Value: start | middle | end | inherit
//Initial: start
//Applies to: 'text' IXMLElement
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
value = readInheritAttribute(elem, "text-anchor", "start");
if (SVG_TEXT_ANCHORS.get(value) != null) {
TEXT_ANCHOR.put(a, SVG_TEXT_ANCHORS.get(value));
}
//'display-align'
//Value: auto | before | center | after | inherit
//Initial: auto
//Applies to: 'textArea'
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
value = readInheritAttribute(elem, "display-align", "auto");
// XXX - Implement me properly
if (!value.equals("auto")) {
if (value.equals("center")) {
TEXT_ANCHOR.put(a, TextAnchor.MIDDLE);
} else if (value.equals("before")) {
TEXT_ANCHOR.put(a, TextAnchor.END);
}
}
//text-align
//Value: start | end | center | inherit
//Initial: start
//Applies to: textArea elements
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes
value = readInheritAttribute(elem, "text-align", "start");
// XXX - Implement me properly
if (!value.equals("start")) {
TEXT_ALIGN.put(a, SVG_TEXT_ALIGNS.get(value));
}
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
private void readTextFlowAttributes(IXMLElement elem, HashMap<AttributeKey, Object> a)
throws IOException {
Object value;
//'line-increment'
//Value: auto | <number> | inherit
//Initial: auto
//Applies to: 'textArea'
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
value = readInheritAttribute(elem, "line-increment", "auto");
if (DEBUG) {
System.out.println("SVGInputFormat not implemented line-increment=" + value);
}
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
private void readTransformAttribute(IXMLElement elem, HashMap<AttributeKey, Object> a)
throws IOException {
String value;
value = readAttribute(elem, "transform", "none");
if (!value.equals("none")) {
TRANSFORM.put(a, toTransform(elem, value));
}
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
private void readSolidColorElement(IXMLElement elem)
throws IOException {
HashMap<AttributeKey, Object> a = new HashMap<AttributeKey, Object>();
readCoreAttributes(elem, a);
// 'solid-color'
//Value: currentColor | <color> | inherit
//Initial: black
//Applies to: 'solidColor' elements
//Inherited: no
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified <color> value, except inherit
Color color = toColor(elem, readAttribute(elem, "solid-color", "black"));
//'solid-opacity'
//Value: <opacity-value> | inherit
//Initial: 1
//Applies to: 'solidColor' elements
//Inherited: no
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
double opacity = toDouble(elem, readAttribute(elem, "solid-opacity", "1"), 1, 0, 1);
if (opacity != 1) {
color = new Color(((int) (255 * opacity) << 24) | (0xffffff & color.getRGB()), true);
}
elementObjects.put(elem, color);
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
private void readShapeAttributes(IXMLElement elem, HashMap<AttributeKey, Object> a)
throws IOException {
Object objectValue;
String value;
double doubleValue;
//'color'
// Value: <color> | inherit
// Initial: depends on user agent
// Applies to: None. Indirectly affects other properties via currentColor
// Inherited: yes
// Percentages: N/A
// Media: visual
// Animatable: yes
// Computed value: Specified <color> value, except inherit
//
// value = readInheritAttribute(elem, "color", "black");
// if (DEBUG) System.out.println("color="+value);
//'color-rendering'
// Value: auto | optimizeSpeed | optimizeQuality | inherit
// Initial: auto
// Applies to: container elements , graphics elements and 'animateColor'
// Inherited: yes
// Percentages: N/A
// Media: visual
// Animatable: yes
// Computed value: Specified value, except inherit
//
// value = readInheritAttribute(elem, "color-rendering", "auto");
// if (DEBUG) System.out.println("color-rendering="+value);
// 'fill'
// Value: <paint> | inherit (See Specifying paint)
// Initial: black
// Applies to: shapes and text content elements
// Inherited: yes
// Percentages: N/A
// Media: visual
// Animatable: yes
// Computed value: "none", system paint, specified <color> value or absolute IRI
objectValue = toPaint(elem, readInheritColorAttribute(elem, "fill", "black"));
if (objectValue instanceof Color) {
FILL_COLOR.put(a, (Color) objectValue);
} else if (objectValue instanceof Gradient) {
FILL_GRADIENT.putClone(a, (Gradient) objectValue);
} else if (objectValue == null) {
FILL_COLOR.put(a, null);
} else {
FILL_COLOR.put(a, null);
if (DEBUG) {
System.out.println("SVGInputFormat not implemented fill=" + objectValue);
}
}
//'fill-opacity'
//Value: <opacity-value> | inherit
//Initial: 1
//Applies to: shapes and text content elements
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
objectValue = readInheritAttribute(elem, "fill-opacity", "1");
FILL_OPACITY.put(a, toDouble(elem, (String) objectValue, 1d, 0d, 1d));
// 'fill-rule'
// Value: nonzero | evenodd | inherit
// Initial: nonzero
// Applies to: shapes and text content elements
// Inherited: yes
// Percentages: N/A
// Media: visual
// Animatable: yes
// Computed value: Specified value, except inherit
value = readInheritAttribute(elem, "fill-rule", "nonzero");
WINDING_RULE.put(a, SVG_FILL_RULES.get(value));
//'stroke'
//Value: <paint> | inherit (See Specifying paint)
//Initial: none
//Applies to: shapes and text content elements
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: "none", system paint, specified <color> value
// or absolute IRI
objectValue = toPaint(elem, readInheritColorAttribute(elem, "stroke", "none"));
if (objectValue instanceof Color) {
STROKE_COLOR.put(a, (Color) objectValue);
} else if (objectValue instanceof Gradient) {
STROKE_GRADIENT.putClone(a, (Gradient) objectValue);
} else if (objectValue == null) {
STROKE_COLOR.put(a, null);
} else {
STROKE_COLOR.put(a, null);
if (DEBUG) {
System.out.println("SVGInputFormat not implemented stroke=" + objectValue);
}
}
//'stroke-dasharray'
//Value: none | <dasharray> | inherit
//Initial: none
//Applies to: shapes and text content elements
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes (non-additive)
//Computed value: Specified value, except inherit
value = readInheritAttribute(elem, "stroke-dasharray", "none");
if (!value.equals("none")) {
String[] values = toWSOrCommaSeparatedArray(value);
double[] dashes = new double[values.length];
for (int i = 0; i < values.length; i++) {
dashes[i] = toNumber(elem, values[i]);
}
STROKE_DASHES.put(a, dashes);
}
//'stroke-dashoffset'
//Value: <length> | inherit
//Initial: 0
//Applies to: shapes and text content elements
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
doubleValue = toNumber(elem, readInheritAttribute(elem, "stroke-dashoffset", "0"));
STROKE_DASH_PHASE.put(a, doubleValue);
IS_STROKE_DASH_FACTOR.put(a, false);
//'stroke-linecap'
//Value: butt | round | square | inherit
//Initial: butt
//Applies to: shapes and text content elements
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
value = readInheritAttribute(elem, "stroke-linecap", "butt");
STROKE_CAP.put(a, SVG_STROKE_LINECAPS.get(value));
//'stroke-linejoin'
//Value: miter | round | bevel | inherit
//Initial: miter
//Applies to: shapes and text content elements
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
value = readInheritAttribute(elem, "stroke-linejoin", "miter");
STROKE_JOIN.put(a, SVG_STROKE_LINEJOINS.get(value));
//'stroke-miterlimit'
//Value: <miterlimit> | inherit
//Initial: 4
//Applies to: shapes and text content elements
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
doubleValue = toDouble(elem, readInheritAttribute(elem, "stroke-miterlimit", "4"), 4d, 1d, Double.MAX_VALUE);
STROKE_MITER_LIMIT.put(a, doubleValue);
IS_STROKE_MITER_LIMIT_FACTOR.put(a, false);
//'stroke-opacity'
//Value: <opacity-value> | inherit
//Initial: 1
//Applies to: shapes and text content elements
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
objectValue = readInheritAttribute(elem, "stroke-opacity", "1");
STROKE_OPACITY.put(a, toDouble(elem, (String) objectValue, 1d, 0d, 1d));
//'stroke-width'
//Value: <length> | inherit
//Initial: 1
//Applies to: shapes and text content elements
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
doubleValue = toNumber(elem, readInheritAttribute(elem, "stroke-width", "1"));
STROKE_WIDTH.put(a, doubleValue);
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
private void readUseShapeAttributes(IXMLElement elem, HashMap<AttributeKey, Object> a)
throws IOException {
Object objectValue;
String value;
double doubleValue;
//'color'
// Value: <color> | inherit
// Initial: depends on user agent
// Applies to: None. Indirectly affects other properties via currentColor
// Inherited: yes
// Percentages: N/A
// Media: visual
// Animatable: yes
// Computed value: Specified <color> value, except inherit
//
// value = readInheritAttribute(elem, "color", "black");
// if (DEBUG) System.out.println("color="+value);
//'color-rendering'
// Value: auto | optimizeSpeed | optimizeQuality | inherit
// Initial: auto
// Applies to: container elements , graphics elements and 'animateColor'
// Inherited: yes
// Percentages: N/A
// Media: visual
// Animatable: yes
// Computed value: Specified value, except inherit
//
// value = readInheritAttribute(elem, "color-rendering", "auto");
// if (DEBUG) System.out.println("color-rendering="+value);
// 'fill'
// Value: <paint> | inherit (See Specifying paint)
// Initial: black
// Applies to: shapes and text content elements
// Inherited: yes
// Percentages: N/A
// Media: visual
// Animatable: yes
// Computed value: "none", system paint, specified <color> value or absolute IRI
objectValue = readInheritColorAttribute(elem, "fill", null);
if (objectValue != null) {
objectValue = toPaint(elem, (String) objectValue);
if (objectValue instanceof Color) {
FILL_COLOR.put(a, (Color) objectValue);
} else if (objectValue instanceof Gradient) {
FILL_GRADIENT.put(a, (Gradient) objectValue);
} else if (objectValue == null) {
FILL_COLOR.put(a, null);
} else {
FILL_COLOR.put(a, null);
if (DEBUG) {
System.out.println("SVGInputFormat not implemented fill=" + objectValue);
}
}
}
//'fill-opacity'
//Value: <opacity-value> | inherit
//Initial: 1
//Applies to: shapes and text content elements
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
objectValue = readInheritAttribute(elem, "fill-opacity", null);
if (objectValue != null) {
FILL_OPACITY.put(a, toDouble(elem, (String) objectValue, 1d, 0d, 1d));
}
// 'fill-rule'
// Value: nonzero | evenodd | inherit
// Initial: nonzero
// Applies to: shapes and text content elements
// Inherited: yes
// Percentages: N/A
// Media: visual
// Animatable: yes
// Computed value: Specified value, except inherit
value = readInheritAttribute(elem, "fill-rule", null);
if (value != null) {
WINDING_RULE.put(a, SVG_FILL_RULES.get(value));
}
//'stroke'
//Value: <paint> | inherit (See Specifying paint)
//Initial: none
//Applies to: shapes and text content elements
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: "none", system paint, specified <color> value
// or absolute IRI
objectValue = toPaint(elem, readInheritColorAttribute(elem, "stroke", null));
if (objectValue != null) {
if (objectValue instanceof Color) {
STROKE_COLOR.put(a, (Color) objectValue);
} else if (objectValue instanceof Gradient) {
STROKE_GRADIENT.put(a, (Gradient) objectValue);
}
}
//'stroke-dasharray'
//Value: none | <dasharray> | inherit
//Initial: none
//Applies to: shapes and text content elements
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes (non-additive)
//Computed value: Specified value, except inherit
value = readInheritAttribute(elem, "stroke-dasharray", null);
if (value != null && !value.equals("none")) {
String[] values = toCommaSeparatedArray(value);
double[] dashes = new double[values.length];
for (int i = 0; i < values.length; i++) {
dashes[i] = toNumber(elem, values[i]);
}
STROKE_DASHES.put(a, dashes);
}
//'stroke-dashoffset'
//Value: <length> | inherit
//Initial: 0
//Applies to: shapes and text content elements
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
objectValue = readInheritAttribute(elem, "stroke-dashoffset", null);
if (objectValue != null) {
doubleValue = toNumber(elem, (String) objectValue);
STROKE_DASH_PHASE.put(a, doubleValue);
IS_STROKE_DASH_FACTOR.put(a, false);
}
//'stroke-linecap'
//Value: butt | round | square | inherit
//Initial: butt
//Applies to: shapes and text content elements
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
value = readInheritAttribute(elem, "stroke-linecap", null);
if (value != null) {
STROKE_CAP.put(a, SVG_STROKE_LINECAPS.get(value));
}
//'stroke-linejoin'
//Value: miter | round | bevel | inherit
//Initial: miter
//Applies to: shapes and text content elements
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
value = readInheritAttribute(elem, "stroke-linejoin", null);
if (value != null) {
STROKE_JOIN.put(a, SVG_STROKE_LINEJOINS.get(value));
}
//'stroke-miterlimit'
//Value: <miterlimit> | inherit
//Initial: 4
//Applies to: shapes and text content elements
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
objectValue = readInheritAttribute(elem, "stroke-miterlimit", null);
if (objectValue != null) {
doubleValue = toDouble(elem, (String) objectValue, 4d, 1d, Double.MAX_VALUE);
STROKE_MITER_LIMIT.put(a, doubleValue);
IS_STROKE_MITER_LIMIT_FACTOR.put(a, false);
}
//'stroke-opacity'
//Value: <opacity-value> | inherit
//Initial: 1
//Applies to: shapes and text content elements
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
objectValue = readInheritAttribute(elem, "stroke-opacity", null);
if (objectValue != null) {
STROKE_OPACITY.put(a, toDouble(elem, (String) objectValue, 1d, 0d, 1d));
}
//'stroke-width'
//Value: <length> | inherit
//Initial: 1
//Applies to: shapes and text content elements
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
objectValue = readInheritAttribute(elem, "stroke-width", null);
if (objectValue != null) {
doubleValue = toNumber(elem, (String) objectValue);
STROKE_WIDTH.put(a, doubleValue);
}
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
private void readLineAttributes(IXMLElement elem, HashMap<AttributeKey, Object> a)
throws IOException {
Object objectValue;
String value;
double doubleValue;
//'color'
// Value: <color> | inherit
// Initial: depends on user agent
// Applies to: None. Indirectly affects other properties via currentColor
// Inherited: yes
// Percentages: N/A
// Media: visual
// Animatable: yes
// Computed value: Specified <color> value, except inherit
//
// value = readInheritAttribute(elem, "color", "black");
// if (DEBUG) System.out.println("color="+value);
//'color-rendering'
// Value: auto | optimizeSpeed | optimizeQuality | inherit
// Initial: auto
// Applies to: container elements , graphics elements and 'animateColor'
// Inherited: yes
// Percentages: N/A
// Media: visual
// Animatable: yes
// Computed value: Specified value, except inherit
//
// value = readInheritAttribute(elem, "color-rendering", "auto");
// if (DEBUG) System.out.println("color-rendering="+value);
// 'fill'
// Value: <paint> | inherit (See Specifying paint)
// Initial: black
// Applies to: shapes and text content elements
// Inherited: yes
// Percentages: N/A
// Media: visual
// Animatable: yes
// Computed value: "none", system paint, specified <color> value or absolute IRI
objectValue = toPaint(elem, readInheritColorAttribute(elem, "fill", "none"));
if (objectValue instanceof Color) {
FILL_COLOR.put(a, (Color) objectValue);
} else if (objectValue instanceof Gradient) {
FILL_GRADIENT.putClone(a, (Gradient) objectValue);
} else if (objectValue == null) {
FILL_COLOR.put(a, null);
} else {
FILL_COLOR.put(a, null);
if (DEBUG) {
System.out.println("SVGInputFormat not implemented fill=" + objectValue);
}
}
//'fill-opacity'
//Value: <opacity-value> | inherit
//Initial: 1
//Applies to: shapes and text content elements
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
objectValue = readInheritAttribute(elem, "fill-opacity", "1");
FILL_OPACITY.put(a, toDouble(elem, (String) objectValue, 1d, 0d, 1d));
// 'fill-rule'
// Value: nonzero | evenodd | inherit
// Initial: nonzero
// Applies to: shapes and text content elements
// Inherited: yes
// Percentages: N/A
// Media: visual
// Animatable: yes
// Computed value: Specified value, except inherit
value = readInheritAttribute(elem, "fill-rule", "nonzero");
WINDING_RULE.put(a, SVG_FILL_RULES.get(value));
//'stroke'
//Value: <paint> | inherit (See Specifying paint)
//Initial: none
//Applies to: shapes and text content elements
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: "none", system paint, specified <color> value
// or absolute IRI
objectValue = toPaint(elem, readInheritColorAttribute(elem, "stroke", "black"));
if (objectValue instanceof Color) {
STROKE_COLOR.put(a, (Color) objectValue);
} else if (objectValue instanceof Gradient) {
STROKE_GRADIENT.putClone(a, (Gradient) objectValue);
} else if (objectValue == null) {
STROKE_COLOR.put(a, null);
} else {
STROKE_COLOR.put(a, null);
if (DEBUG) {
System.out.println("SVGInputFormat not implemented stroke=" + objectValue);
}
}
//'stroke-dasharray'
//Value: none | <dasharray> | inherit
//Initial: none
//Applies to: shapes and text content elements
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes (non-additive)
//Computed value: Specified value, except inherit
value = readInheritAttribute(elem, "stroke-dasharray", "none");
if (!value.equals("none")) {
String[] values = toWSOrCommaSeparatedArray(value);
double[] dashes = new double[values.length];
for (int i = 0; i < values.length; i++) {
dashes[i] = toNumber(elem, values[i]);
}
STROKE_DASHES.put(a, dashes);
}
//'stroke-dashoffset'
//Value: <length> | inherit
//Initial: 0
//Applies to: shapes and text content elements
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
doubleValue = toNumber(elem, readInheritAttribute(elem, "stroke-dashoffset", "0"));
STROKE_DASH_PHASE.put(a, doubleValue);
IS_STROKE_DASH_FACTOR.put(a, false);
//'stroke-linecap'
//Value: butt | round | square | inherit
//Initial: butt
//Applies to: shapes and text content elements
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
value = readInheritAttribute(elem, "stroke-linecap", "butt");
STROKE_CAP.put(a, SVG_STROKE_LINECAPS.get(value));
//'stroke-linejoin'
//Value: miter | round | bevel | inherit
//Initial: miter
//Applies to: shapes and text content elements
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
value = readInheritAttribute(elem, "stroke-linejoin", "miter");
STROKE_JOIN.put(a, SVG_STROKE_LINEJOINS.get(value));
//'stroke-miterlimit'
//Value: <miterlimit> | inherit
//Initial: 4
//Applies to: shapes and text content elements
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
doubleValue = toDouble(elem, readInheritAttribute(elem, "stroke-miterlimit", "4"), 4d, 1d, Double.MAX_VALUE);
STROKE_MITER_LIMIT.put(a, doubleValue);
IS_STROKE_MITER_LIMIT_FACTOR.put(a, false);
//'stroke-opacity'
//Value: <opacity-value> | inherit
//Initial: 1
//Applies to: shapes and text content elements
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
objectValue = readInheritAttribute(elem, "stroke-opacity", "1");
STROKE_OPACITY.put(a, toDouble(elem, (String) objectValue, 1d, 0d, 1d));
//'stroke-width'
//Value: <length> | inherit
//Initial: 1
//Applies to: shapes and text content elements
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
doubleValue = toNumber(elem, readInheritAttribute(elem, "stroke-width", "1"));
STROKE_WIDTH.put(a, doubleValue);
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
private void readViewportAttributes(IXMLElement elem, HashMap<AttributeKey, Object> a)
throws IOException {
Object value;
Double doubleValue;
// width of the viewport
value = readAttribute(elem, "width", null);
if (DEBUG) {
System.out.println("SVGInputFormat READ viewport w/h factors:" + viewportStack.peek().widthPercentFactor + "," + viewportStack.peek().heightPercentFactor);
}
if (value != null) {
doubleValue = toLength(elem, (String) value, viewportStack.peek().widthPercentFactor);
VIEWPORT_WIDTH.put(a, doubleValue);
}
// height of the viewport
value = readAttribute(elem, "height", null);
if (value != null) {
doubleValue = toLength(elem, (String) value, viewportStack.peek().heightPercentFactor);
VIEWPORT_HEIGHT.put(a, doubleValue);
}
//'viewport-fill'
//Value: "none" | <color> | inherit
//Initial: none
//Applies to: viewport-creating elements
//Inherited: no
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: "none" or specified <color> value, except inherit
value = toPaint(elem, readInheritColorAttribute(elem, "viewport-fill", "none"));
if (value == null || (value instanceof Color)) {
VIEWPORT_FILL.put(a, (Color) value);
}
//'viewport-fill-opacity'
//Value: <opacity-value> | inherit
//Initial: 1.0
//Applies to: viewport-creating elements
//Inherited: no
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
doubleValue = toDouble(elem, readAttribute(elem, "viewport-fill-opacity", "1.0"));
VIEWPORT_FILL_OPACITY.put(a, doubleValue);
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
private void readGraphicsAttributes(IXMLElement elem, Figure f)
throws IOException {
Object value;
// 'display'
// Value: inline | block | list-item |
// run-in | compact | marker |
// table | inline-table | table-row-group | table-header-group |
// table-footer-group | table-row | table-column-group | table-column |
// table-cell | table-caption | none | inherit
// Initial: inline
// Applies to: 'svg' , 'g' , 'switch' , 'a' , 'foreignObject' ,
// graphics elements (including the text content block elements) and text
// sub-elements (for example, 'tspan' and 'a' )
// Inherited: no
// Percentages: N/A
// Media: all
// Animatable: yes
// Computed value: Specified value, except inherit
value = readAttribute(elem, "display", "inline");
if (DEBUG) {
System.out.println("SVGInputFormat not implemented display=" + value);
}
//'image-rendering'
//Value: auto | optimizeSpeed | optimizeQuality | inherit
//Initial: auto
//Applies to: images
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
value = readInheritAttribute(elem, "image-rendering", "auto");
if (DEBUG) {
System.out.println("SVGInputFormat not implemented image-rendering=" + value);
}
//'pointer-events'
//Value: boundingBox | visiblePainted | visibleFill | visibleStroke | visible |
//painted | fill | stroke | all | none | inherit
//Initial: visiblePainted
//Applies to: graphics elements
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
value = readInheritAttribute(elem, "pointer-events", "visiblePainted");
if (DEBUG) {
System.out.println("SVGInputFormat not implemented pointer-events=" + value);
}
// 'shape-rendering'
//Value: auto | optimizeSpeed | crispEdges |
//geometricPrecision | inherit
//Initial: auto
//Applies to: shapes
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
value = readInheritAttribute(elem, "shape-rendering", "auto");
if (DEBUG) {
System.out.println("SVGInputFormat not implemented shape-rendering=" + value);
}
//'text-rendering'
//Value: auto | optimizeSpeed | optimizeLegibility |
//geometricPrecision | inherit
//Initial: auto
//Applies to: text content block elements
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
value = readInheritAttribute(elem, "text-rendering", "auto");
if (DEBUG) {
System.out.println("SVGInputFormat not implemented text-rendering=" + value);
}
//'vector-effect'
//Value: non-scaling-stroke | none | inherit
//Initial: none
//Applies to: graphics elements
//Inherited: no
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
value = readAttribute(elem, "vector-effect", "none");
if (DEBUG) {
System.out.println("SVGInputFormat not implemented vector-effect=" + value);
}
//'visibility'
//Value: visible | hidden | collapse | inherit
//Initial: visible
//Applies to: graphics elements (including the text content block
// elements) and text sub-elements (for example, 'tspan' and 'a' )
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
value = readInheritAttribute(elem, "visibility", null);
if (DEBUG) {
System.out.println("SVGInputFormat not implemented visibility=" + value);
}
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
private void readLinearGradientElement(IXMLElement elem)
throws IOException {
HashMap<AttributeKey, Object> a = new HashMap<AttributeKey, Object>();
readCoreAttributes(elem, a);
double x1 = toLength(elem, readAttribute(elem, "x1", "0"), 0.01);
double y1 = toLength(elem, readAttribute(elem, "y1", "0"), 0.01);
double x2 = toLength(elem, readAttribute(elem, "x2", "1"), 0.01);
double y2 = toLength(elem, readAttribute(elem, "y2", "0"), 0.01);
boolean isRelativeToFigureBounds = readAttribute(elem, "gradientUnits", "objectBoundingBox").equals("objectBoundingBox");
ArrayList<IXMLElement> stops = elem.getChildrenNamed("stop", SVG_NAMESPACE);
if (stops.size() == 0) {
stops = elem.getChildrenNamed("stop");
}
if (stops.size() == 0) {
// FIXME - Implement xlink support throughouth SVGInputFormat
String xlink = readAttribute(elem, "xlink:href", "");
if (xlink.startsWith("#")
&& identifiedElements.get(xlink.substring(1)) != null) {
stops = identifiedElements.get(xlink.substring(1)).getChildrenNamed("stop", SVG_NAMESPACE);
if (stops.size() == 0) {
stops = identifiedElements.get(xlink.substring(1)).getChildrenNamed("stop");
}
}
}
if (stops.size() == 0) {
if (DEBUG) {
System.out.println("SVGInpuFormat: Warning no stops in linearGradient " + elem);
}
}
double[] stopOffsets = new double[stops.size()];
Color[] stopColors = new Color[stops.size()];
double[] stopOpacities = new double[stops.size()];
for (int i = 0; i < stops.size(); i++) {
IXMLElement stopElem = stops.get(i);
String offsetStr = readAttribute(stopElem, "offset", "0");
if (offsetStr.endsWith("%")) {
stopOffsets[i] = toDouble(stopElem, offsetStr.substring(0, offsetStr.length() - 1), 0, 0, 100) / 100d;
} else {
stopOffsets[i] = toDouble(stopElem, offsetStr, 0, 0, 1);
}
// 'stop-color'
// Value: currentColor | <color> | inherit
// Initial: black
// Applies to: 'stop' elements
// Inherited: no
// Percentages: N/A
// Media: visual
// Animatable: yes
// Computed value: Specified <color> value, except i
stopColors[i] = toColor(stopElem, readAttribute(stopElem, "stop-color", "black"));
if (stopColors[i] == null) {
stopColors[i] = new Color(0x0, true);
//throw new IOException("stop color missing in "+stopElem);
}
//'stop-opacity'
//Value: <opacity-value> | inherit
//Initial: 1
//Applies to: 'stop' elements
//Inherited: no
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
stopOpacities[i] = toDouble(stopElem, readAttribute(stopElem, "stop-opacity", "1"), 1, 0, 1);
}
AffineTransform tx = toTransform(elem, readAttribute(elem, "gradientTransform", "none"));
Gradient gradient = factory.createLinearGradient(
x1, y1, x2, y2,
stopOffsets, stopColors, stopOpacities,
isRelativeToFigureBounds, tx);
elementObjects.put(elem, gradient);
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
private void readRadialGradientElement(IXMLElement elem)
throws IOException {
HashMap<AttributeKey, Object> a = new HashMap<AttributeKey, Object>();
readCoreAttributes(elem, a);
double cx = toLength(elem, readAttribute(elem, "cx", "0.5"), 0.01);
double cy = toLength(elem, readAttribute(elem, "cy", "0.5"), 0.01);
double fx = toLength(elem, readAttribute(elem, "fx", readAttribute(elem, "cx", "0.5")), 0.01);
double fy = toLength(elem, readAttribute(elem, "fy", readAttribute(elem, "cy", "0.5")), 0.01);
double r = toLength(elem, readAttribute(elem, "r", "0.5"), 0.01);
boolean isRelativeToFigureBounds =
readAttribute(elem, "gradientUnits", "objectBoundingBox").equals("objectBoundingBox");
ArrayList<IXMLElement> stops = elem.getChildrenNamed("stop", SVG_NAMESPACE);
if (stops.size() == 0) {
stops = elem.getChildrenNamed("stop");
}
if (stops.size() == 0) {
// FIXME - Implement xlink support throughout SVGInputFormat
String xlink = readAttribute(elem, "xlink:href", "");
if (xlink.startsWith("#")
&& identifiedElements.get(xlink.substring(1)) != null) {
stops = identifiedElements.get(xlink.substring(1)).getChildrenNamed("stop", SVG_NAMESPACE);
if (stops.size() == 0) {
stops = identifiedElements.get(xlink.substring(1)).getChildrenNamed("stop");
}
}
}
double[] stopOffsets = new double[stops.size()];
Color[] stopColors = new Color[stops.size()];
double[] stopOpacities = new double[stops.size()];
for (int i = 0; i < stops.size(); i++) {
IXMLElement stopElem = stops.get(i);
String offsetStr = readAttribute(stopElem, "offset", "0");
if (offsetStr.endsWith("%")) {
stopOffsets[i] = toDouble(stopElem, offsetStr.substring(0, offsetStr.length() - 1), 0, 0, 100) / 100d;
} else {
stopOffsets[i] = toDouble(stopElem, offsetStr, 0, 0, 1);
}
// 'stop-color'
// Value: currentColor | <color> | inherit
// Initial: black
// Applies to: 'stop' elements
// Inherited: no
// Percentages: N/A
// Media: visual
// Animatable: yes
// Computed value: Specified <color> value, except i
stopColors[i] = toColor(stopElem, readAttribute(stopElem, "stop-color", "black"));
if (stopColors[i] == null) {
stopColors[i] = new Color(0x0, true);
//throw new IOException("stop color missing in "+stopElem);
}
//'stop-opacity'
//Value: <opacity-value> | inherit
//Initial: 1
//Applies to: 'stop' elements
//Inherited: no
//Percentages: N/A
//Media: visual
//Animatable: yes
//Computed value: Specified value, except inherit
stopOpacities[i] = toDouble(stopElem, readAttribute(stopElem, "stop-opacity", "1"), 1, 0, 1);
}
AffineTransform tx = toTransform(elem, readAttribute(elem, "gradientTransform", "none"));
Gradient gradient = factory.createRadialGradient(
cx, cy, fx, fy, r,
stopOffsets, stopColors, stopOpacities,
isRelativeToFigureBounds,
tx);
elementObjects.put(elem, gradient);
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
private void readFontAttributes(IXMLElement elem, Map<AttributeKey, Object> a)
throws IOException {
String value;
double doubleValue;
// 'font-family'
// Value: [[ <family-name> |
// <generic-family> ],]* [<family-name> |
// <generic-family>] | inherit
// Initial: depends on user agent
// Applies to: text content elements
// Inherited: yes
// Percentages: N/A
// Media: visual
// Animatable: yes
// Computed value: Specified value, except inherit
value = readInheritAttribute(elem, "font-family", "Dialog");
String[] familyNames = toQuotedAndCommaSeparatedArray(value);
Font font = null;
// Try to find a font with exactly matching name
for (int i = 0; i < familyNames.length; i++) {
try {
font = (Font) fontFormatter.stringToValue(familyNames[i]);
break;
} catch (ParseException e) {
}
}
if (font == null) {
// Try to create a similar font using the first name in the list
if (familyNames.length > 0) {
fontFormatter.setAllowsUnknownFont(true);
try {
font = (Font) fontFormatter.stringToValue(familyNames[0]);
} catch (ParseException e) {
}
fontFormatter.setAllowsUnknownFont(false);
}
}
if (font == null) {
// Fallback to the system Dialog font
font = new Font("Dialog", Font.PLAIN, 12);
}
FONT_FACE.put(a, font);
// 'font-getChildCount'
// Value: <absolute-getChildCount> | <relative-getChildCount> |
// <length> | inherit
// Initial: medium
// Applies to: text content elements
// Inherited: yes, the computed value is inherited
// Percentages: N/A
// Media: visual
// Animatable: yes
// Computed value: Absolute length
doubleValue = readInheritFontSizeAttribute(elem, "font-size", "medium");
FONT_SIZE.put(a, doubleValue);
// 'font-style'
// Value: normal | italic | oblique | inherit
// Initial: normal
// Applies to: text content elements
// Inherited: yes
// Percentages: N/A
// Media: visual
// Animatable: yes
// Computed value: Specified value, except inherit
value = readInheritAttribute(elem, "font-style", "normal");
FONT_ITALIC.put(a, value.equals("italic"));
//'font-variant'
//Value: normal | small-caps | inherit
//Initial: normal
//Applies to: text content elements
//Inherited: yes
//Percentages: N/A
//Media: visual
//Animatable: no
//Computed value: Specified value, except inherit
value = readInheritAttribute(elem, "font-variant", "normal");
// if (DEBUG) System.out.println("font-variant="+value);
// 'font-weight'
// Value: normal | bold | bolder | lighter | 100 | 200 | 300
// | 400 | 500 | 600 | 700 | 800 | 900 | inherit
// Initial: normal
// Applies to: text content elements
// Inherited: yes
// Percentages: N/A
// Media: visual
// Animatable: yes
// Computed value: one of the legal numeric values, non-numeric
// values shall be converted to numeric values according to the rules
// defined below.
value = readInheritAttribute(elem, "font-weight", "normal");
FONT_BOLD.put(a, value.equals("bold") || value.equals("bolder")
|| value.equals("400") || value.equals("500") || value.equals("600")
|| value.equals("700") || value.equals("800") || value.equals("900"));
// Note: text-decoration is an SVG 1.1 feature
//'text-decoration'
//Value: none | [ underline || overline || line-through || blink ] | inherit
//Initial: none
//Applies to: text content elements
//Inherited: no (see prose)
//Percentages: N/A
//Media: visual
//Animatable: yes
value = readAttribute(elem, "text-decoration", "none");
FONT_UNDERLINE.put(a, value.equals("underline"));
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
Nullable
private Object toPaint(IXMLElement elem, String value) throws IOException {
String str = value;
if (str == null) {
return null;
}
str = str.trim().toLowerCase();
if (str.equals("none")) {
return null;
} else if (str.equals("currentcolor")) {
String currentColor = readInheritAttribute(elem, "color", "black");
if (currentColor == null || currentColor.trim().toLowerCase().equals("currentColor")) {
return null;
} else {
return toPaint(elem, currentColor);
}
} else if (SVG_COLORS.containsKey(str)) {
return SVG_COLORS.get(str);
} else if (str.startsWith("#") && str.length() == 7) {
return new Color(Integer.decode(str));
} else if (str.startsWith("#") && str.length() == 4) {
// Three digits hex value
int th = Integer.decode(str);
return new Color(
(th & 0xf) | ((th & 0xf) << 4)
| ((th & 0xf0) << 4) | ((th & 0xf0) << 8)
| ((th & 0xf00) << 8) | ((th & 0xf00) << 12));
} else if (str.startsWith("rgb")) {
try {
StringTokenizer tt = new StringTokenizer(str, "() ,");
tt.nextToken();
String r = tt.nextToken();
String g = tt.nextToken();
String b = tt.nextToken();
Color c = new Color(
r.endsWith("%") ? (int) (Double.parseDouble(r.substring(0, r.length() - 1)) * 2.55) : Integer.decode(r),
g.endsWith("%") ? (int) (Double.parseDouble(g.substring(0, g.length() - 1)) * 2.55) : Integer.decode(g),
b.endsWith("%") ? (int) (Double.parseDouble(b.substring(0, b.length() - 1)) * 2.55) : Integer.decode(b));
return c;
} catch (Exception e) {
/*if (DEBUG)*/ System.out.println("SVGInputFormat.toPaint illegal RGB value " + str);
e.printStackTrace();
return null;
}
} else if (str.startsWith("url(")) {
String href = value.substring(4, value.length() - 1);
if (identifiedElements.containsKey(href.substring(1))
&& elementObjects.containsKey(identifiedElements.get(href.substring(1)))) {
Object obj = elementObjects.get(identifiedElements.get(href.substring(1)));
return obj;
}
// XXX - Implement me
if (DEBUG) {
System.out.println("SVGInputFormat.toPaint not implemented for " + href);
}
return null;
} else {
return null;
}
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
Nullable
private Color toColor(IXMLElement elem, String value) throws IOException {
String str = value;
if (str == null) {
return null;
}
str = str.trim().toLowerCase();
if (str.equals("currentcolor")) {
String currentColor = readInheritAttribute(elem, "color", "black");
if (currentColor == null || currentColor.trim().toLowerCase().equals("currentColor")) {
return null;
} else {
return toColor(elem, currentColor);
}
} else if (SVG_COLORS.containsKey(str)) {
return SVG_COLORS.get(str);
} else if (str.startsWith("#") && str.length() == 7) {
return new Color(Integer.decode(str));
} else if (str.startsWith("#") && str.length() == 4) {
// Three digits hex value
int th = Integer.decode(str);
return new Color(
(th & 0xf) | ((th & 0xf) << 4)
| ((th & 0xf0) << 4) | ((th & 0xf0) << 8)
| ((th & 0xf00) << 8) | ((th & 0xf00) << 12));
} else if (str.startsWith("rgb")) {
try {
StringTokenizer tt = new StringTokenizer(str, "() ,");
tt.nextToken();
String r = tt.nextToken();
String g = tt.nextToken();
String b = tt.nextToken();
Color c = new Color(
r.endsWith("%") ? (int) (Integer.decode(r.substring(0, r.length() - 1)) * 2.55) : Integer.decode(r),
g.endsWith("%") ? (int) (Integer.decode(g.substring(0, g.length() - 1)) * 2.55) : Integer.decode(g),
b.endsWith("%") ? (int) (Integer.decode(b.substring(0, b.length() - 1)) * 2.55) : Integer.decode(b));
return c;
} catch (Exception e) {
if (DEBUG) {
System.out.println("SVGInputFormat.toColor illegal RGB value " + str);
}
return null;
}
} else if (str.startsWith("url")) {
// FIXME - Implement me
if (DEBUG) {
System.out.println("SVGInputFormat.toColor not implemented for " + str);
}
return null;
} else {
return null;
}
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
private double toDouble(IXMLElement elem, String value) throws IOException {
return toDouble(elem, value, 0, Double.MIN_VALUE, Double.MAX_VALUE);
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
private double toDouble(IXMLElement elem, String value, double defaultValue, double min, double max) throws IOException {
try {
double d = Double.valueOf(value);
return Math.max(Math.min(d, max), min);
} catch (NumberFormatException e) {
return defaultValue;
/*
IOException ex = new IOException(elem.getTagName()+"@"+elem.getLineNr()+" "+e.getMessage());
ex.initCause(e);
throw ex;*/
}
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
private String toText(IXMLElement elem, String value) throws IOException {
String space = readInheritAttribute(elem, "xml:space", "default");
if (space.equals("default")) {
return value.trim().replaceAll("\\s++", " ");
} else /*if (space.equals("preserve"))*/ {
return value;
}
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
public static AffineTransform toTransform(IXMLElement elem, String str) throws IOException {
AffineTransform t = new AffineTransform();
if (str != null && !str.equals("none")) {
StreamPosTokenizer tt = new StreamPosTokenizer(new StringReader(str));
tt.resetSyntax();
tt.wordChars('a', 'z');
tt.wordChars('A', 'Z');
tt.wordChars(128 + 32, 255);
tt.whitespaceChars(0, ' ');
tt.whitespaceChars(',', ',');
tt.parseNumbers();
tt.parseExponents();
while (tt.nextToken() != StreamPosTokenizer.TT_EOF) {
if (tt.ttype != StreamPosTokenizer.TT_WORD) {
throw new IOException("Illegal transform " + str);
}
String type = tt.sval;
if (tt.nextToken() != '(') {
throw new IOException("'(' not found in transform " + str);
}
if (type.equals("matrix")) {
double[] m = new double[6];
for (int i = 0; i < 6; i++) {
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("Matrix value " + i + " not found in transform " + str + " token:" + tt.ttype + " " + tt.sval);
}
m[i] = tt.nval;
}
t.concatenate(new AffineTransform(m));
} else if (type.equals("translate")) {
double tx, ty;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("X-translation value not found in transform " + str);
}
tx = tt.nval;
if (tt.nextToken() == StreamPosTokenizer.TT_NUMBER) {
ty = tt.nval;
} else {
tt.pushBack();
ty = 0;
}
t.translate(tx, ty);
} else if (type.equals("scale")) {
double sx, sy;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("X-scale value not found in transform " + str);
}
sx = tt.nval;
if (tt.nextToken() == StreamPosTokenizer.TT_NUMBER) {
sy = tt.nval;
} else {
tt.pushBack();
sy = sx;
}
t.scale(sx, sy);
} else if (type.equals("rotate")) {
double angle, cx, cy;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("Angle value not found in transform " + str);
}
angle = tt.nval;
if (tt.nextToken() == StreamPosTokenizer.TT_NUMBER) {
cx = tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("Y-center value not found in transform " + str);
}
cy = tt.nval;
} else {
tt.pushBack();
cx = cy = 0;
}
t.rotate(angle * Math.PI / 180d, cx, cy);
} else if (type.equals("skewX")) {
double angle;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("Skew angle not found in transform " + str);
}
angle = tt.nval;
t.concatenate(new AffineTransform(
1, 0, Math.tan(angle * Math.PI / 180), 1, 0, 0));
} else if (type.equals("skewY")) {
double angle;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("Skew angle not found in transform " + str);
}
angle = tt.nval;
t.concatenate(new AffineTransform(
1, Math.tan(angle * Math.PI / 180), 0, 1, 0, 0));
} else if (type.equals("ref")) {
System.err.println("SVGInputFormat warning: ignored ref(...) transform attribute in element " + elem);
while (tt.nextToken() != ')' && tt.ttype != StreamPosTokenizer.TT_EOF) {
// ignore tokens between brackets
}
tt.pushBack();
} else {
throw new IOException("Unknown transform " + type + " in " + str + " in element " + elem);
}
if (tt.nextToken() != ')') {
throw new IOException("')' not found in transform " + str);
}
}
}
return t;
}
// in java/org/jhotdraw/samples/svg/io/SVGInputFormat.java
Override
public void read(Transferable t, Drawing drawing, boolean replace) throws UnsupportedFlavorException, IOException {
InputStream in = (InputStream) t.getTransferData(new DataFlavor("image/svg+xml", "Image SVG"));
try {
read(in, drawing, false);
} finally {
in.close();
}
}
// in java/org/jhotdraw/samples/svg/io/ImageMapOutputFormat.java
Override
public void write(URI uri, Drawing drawing) throws IOException {
write(new File(uri),drawing);
}
// in java/org/jhotdraw/samples/svg/io/ImageMapOutputFormat.java
public void write(File file, Drawing drawing) throws IOException {
BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream(file));
try {
write(out, drawing);
} finally {
out.close();
}
}
// in java/org/jhotdraw/samples/svg/io/ImageMapOutputFormat.java
Override
public void write(OutputStream out, Drawing drawing) throws IOException {
write(out, drawing.getChildren());
}
// in java/org/jhotdraw/samples/svg/io/ImageMapOutputFormat.java
public void write(OutputStream out, Drawing drawing,
AffineTransform drawingTransform, Dimension imageSize) throws IOException {
write(out, drawing.getChildren(), drawingTransform, imageSize);
}
// in java/org/jhotdraw/samples/svg/io/ImageMapOutputFormat.java
public void write(OutputStream out, java.util.List<Figure> figures,
AffineTransform drawingTransform, Dimension imageSize) throws IOException {
this.drawingTransform = (drawingTransform == null) ? new AffineTransform() : drawingTransform;
this.bounds = (imageSize == null) ? new Rectangle(0, 0, Integer.MAX_VALUE, Integer.MAX_VALUE) : new Rectangle(0, 0, imageSize.width, imageSize.height);
XMLElement document = new XMLElement("map");
// Note: Image map elements need to be written from front to back
for (Figure f : new ReversedList<Figure>(figures)) {
writeElement(document, f);
}
// Strip AREA elements with "nohref" attributes from the end of the
// map
if (!isIncludeNohref) {
for (int i = document.getChildrenCount() - 1; i >= 0; i--) {
XMLElement child = (XMLElement) document.getChildAtIndex(i);
if (child.hasAttribute("nohref")) {
document.removeChildAtIndex(i);
}
}
}
// Write XML content
PrintWriter writer = new PrintWriter(
new OutputStreamWriter(out, "UTF-8"));
//new XMLWriter(writer).write(document);
for (Object o : document.getChildren()) {
XMLElement child = (XMLElement) o;
new XMLWriter(writer).write(child);
}
// Flush writer
writer.flush();
}
// in java/org/jhotdraw/samples/svg/io/ImageMapOutputFormat.java
public void write(OutputStream out, java.util.List<Figure> figures) throws IOException {
Rectangle2D.Double drawingRect = null;
for (Figure f : figures) {
if (drawingRect == null) {
drawingRect = f.getBounds();
} else {
drawingRect.add(f.getBounds());
}
}
AffineTransform tx = new AffineTransform();
tx.translate(
-Math.min(0, drawingRect.x),
-Math.min(0, drawingRect.y));
write(out, figures, tx,
new Dimension(
(int) (Math.abs(drawingRect.x) + drawingRect.width),
(int) (Math.abs(drawingRect.y) + drawingRect.height)));
}
// in java/org/jhotdraw/samples/svg/io/ImageMapOutputFormat.java
Override
public Transferable createTransferable(Drawing drawing, java.util.List<Figure> figures, double scaleFactor) throws IOException {
ByteArrayOutputStream buf = new ByteArrayOutputStream();
write(buf, figures);
return new InputStreamTransferable(new DataFlavor("text/html", "HTML Image Map"), buf.toByteArray());
}
// in java/org/jhotdraw/samples/svg/io/ImageMapOutputFormat.java
protected void writeElement(IXMLElement parent, Figure f) throws IOException {
if (f instanceof SVGEllipseFigure) {
writeEllipseElement(parent, (SVGEllipseFigure) f);
} else if (f instanceof SVGGroupFigure) {
writeGElement(parent, (SVGGroupFigure) f);
} else if (f instanceof SVGImageFigure) {
writeImageElement(parent, (SVGImageFigure) f);
} else if (f instanceof SVGPathFigure) {
SVGPathFigure path = (SVGPathFigure) f;
if (path.getChildCount() == 1) {
BezierFigure bezier = (BezierFigure) path.getChild(0);
boolean isLinear = true;
for (int i = 0, n = bezier.getNodeCount(); i < n; i++) {
if (bezier.getNode(i).getMask() != 0) {
isLinear = false;
break;
}
}
if (isLinear) {
if (bezier.isClosed()) {
writePolygonElement(parent, path);
} else {
if (bezier.getNodeCount() == 2) {
writeLineElement(parent, path);
} else {
writePolylineElement(parent, path);
}
}
} else {
writePathElement(parent, path);
}
} else {
writePathElement(parent, path);
}
} else if (f instanceof SVGRectFigure) {
writeRectElement(parent, (SVGRectFigure) f);
} else if (f instanceof SVGTextFigure) {
writeTextElement(parent, (SVGTextFigure) f);
} else if (f instanceof SVGTextAreaFigure) {
writeTextAreaElement(parent, (SVGTextAreaFigure) f);
} else {
System.out.println("Unable to write: " + f);
}
}
// in java/org/jhotdraw/samples/svg/io/ImageMapOutputFormat.java
private void writePathElement(IXMLElement parent, SVGPathFigure f) throws IOException {
GrowStroke growStroke = new GrowStroke( (getStrokeTotalWidth(f) / 2d), getStrokeTotalWidth(f));
BasicStroke basicStroke = new BasicStroke((float) getStrokeTotalWidth(f));
for (Figure child : f.getChildren()) {
SVGBezierFigure bezier = (SVGBezierFigure) child;
IXMLElement elem = parent.createElement("area");
if (bezier.isClosed()) {
writePolyAttributes(elem, f, growStroke.createStrokedShape(bezier.getBezierPath()));
} else {
writePolyAttributes(elem, f, basicStroke.createStrokedShape(bezier.getBezierPath()));
}
parent.addChild(elem);
}
}
// in java/org/jhotdraw/samples/svg/io/ImageMapOutputFormat.java
private void writePolygonElement(IXMLElement parent, SVGPathFigure f) throws IOException {
IXMLElement elem = parent.createElement("area");
if (writePolyAttributes(elem, f, new GrowStroke( (getStrokeTotalWidth(f) / 2d), getStrokeTotalWidth(f)).createStrokedShape(f.getChild(0).getBezierPath()))) {
parent.addChild(elem);
}
}
// in java/org/jhotdraw/samples/svg/io/ImageMapOutputFormat.java
private void writePolylineElement(IXMLElement parent, SVGPathFigure f) throws IOException {
IXMLElement elem = parent.createElement("area");
if (writePolyAttributes(elem, f, new BasicStroke((float) getStrokeTotalWidth(f)).createStrokedShape(f.getChild(0).getBezierPath()))) {
parent.addChild(elem);
}
}
// in java/org/jhotdraw/samples/svg/io/ImageMapOutputFormat.java
private void writeLineElement(IXMLElement parent, SVGPathFigure f) throws IOException {
IXMLElement elem = parent.createElement("area");
if (writePolyAttributes(elem, f, new GrowStroke( (getStrokeTotalWidth(f) / 2d), getStrokeTotalWidth(f)).createStrokedShape(new Line2D.Double(
f.getStartPoint(), f.getEndPoint())))) {
parent.addChild(elem);
}
}
// in java/org/jhotdraw/samples/svg/io/ImageMapOutputFormat.java
private void writeRectElement(IXMLElement parent, SVGRectFigure f) throws IOException {
IXMLElement elem = parent.createElement("AREA");
boolean isContained;
if (f.getArcHeight() == 0 && f.getArcWidth() == 0) {
Rectangle2D.Double rect = f.getBounds();
double grow = getPerpendicularHitGrowth(f);
rect.x -= grow;
rect.y -= grow;
rect.width += grow;
rect.height += grow;
isContained = writeRectAttributes(elem, f, rect);
} else {
isContained = writePolyAttributes(elem, f,
new GrowStroke( (getStrokeTotalWidth(f) / 2d), getStrokeTotalWidth(f)).createStrokedShape(new RoundRectangle2D.Double(
f.getX(), f.getY(), f.getWidth(), f.getHeight(),
f.getArcWidth(), f.getArcHeight())));
}
if (isContained) {
parent.addChild(elem);
}
}
// in java/org/jhotdraw/samples/svg/io/ImageMapOutputFormat.java
private void writeTextElement(IXMLElement parent, SVGTextFigure f) throws IOException {
IXMLElement elem = parent.createElement("AREA");
Rectangle2D.Double rect = f.getBounds();
double grow = getPerpendicularHitGrowth(f);
rect.x -= grow;
rect.y -= grow;
rect.width += grow;
rect.height += grow;
if (writeRectAttributes(elem, f, rect)) {
parent.addChild(elem);
}
}
// in java/org/jhotdraw/samples/svg/io/ImageMapOutputFormat.java
private void writeTextAreaElement(IXMLElement parent, SVGTextAreaFigure f) throws IOException {
IXMLElement elem = parent.createElement("AREA");
Rectangle2D.Double rect = f.getBounds();
double grow = getPerpendicularHitGrowth(f);
rect.x -= grow;
rect.y -= grow;
rect.width += grow;
rect.height += grow;
if (writeRectAttributes(elem, f, rect)) {
parent.addChild(elem);
}
}
// in java/org/jhotdraw/samples/svg/io/ImageMapOutputFormat.java
private void writeEllipseElement(IXMLElement parent, SVGEllipseFigure f) throws IOException {
IXMLElement elem = parent.createElement("area");
Rectangle2D.Double r = f.getBounds();
double grow = getPerpendicularHitGrowth(f);
Ellipse2D.Double ellipse = new Ellipse2D.Double(r.x - grow, r.y - grow, r.width + grow, r.height + grow);
if (writeCircleAttributes(elem, f, ellipse)) {
parent.addChild(elem);
}
}
// in java/org/jhotdraw/samples/svg/io/ImageMapOutputFormat.java
private void writeGElement(IXMLElement parent, SVGGroupFigure f) throws IOException {
// Note: Image map elements need to be written from front to back
for (Figure child : new ReversedList<Figure>(f.getChildren())) {
writeElement(parent, child);
}
}
// in java/org/jhotdraw/samples/svg/SVGCreateFromFileTool.java
Override
public void activate(DrawingEditor editor) {
super.activate(editor);
final DrawingView v=getView();
if (v==null) return;
if (workerThread != null) {
try {
workerThread.join();
} catch (InterruptedException ex) {
// ignore
}
}
final File file;
if (useFileDialog) {
getFileDialog().setVisible(true);
if (getFileDialog().getFile() != null) {
file = new File(getFileDialog().getDirectory(), getFileDialog().getFile());
} else {
file = null;
}
} else {
if (getFileChooser().showOpenDialog(v.getComponent()) == JFileChooser.APPROVE_OPTION) {
file = getFileChooser().getSelectedFile();
} else {
file = null;
}
}
if (file != null) {
Worker worker;
if (file.getName().toLowerCase().endsWith(".svg") ||
file.getName().toLowerCase().endsWith(".svgz")) {
prototype = ((Figure) groupPrototype.clone());
worker = new Worker<Drawing>() {
@Override
public Drawing construct() throws IOException {
Drawing drawing = new DefaultDrawing();
InputFormat in = (file.getName().toLowerCase().endsWith(".svg")) ? new SVGInputFormat() : new SVGZInputFormat();
in.read(file.toURI(), drawing);
return drawing;
}
@Override
protected void done(Drawing drawing) {
CompositeFigure parent;
if (createdFigure == null) {
parent = (CompositeFigure) prototype;
for (Figure f : drawing.getChildren()) {
parent.basicAdd(f);
}
} else {
parent = (CompositeFigure) createdFigure;
parent.willChange();
for (Figure f : drawing.getChildren()) {
parent.add(f);
}
parent.changed();
}
}
@Override
protected void failed(Throwable t) {
JOptionPane.showMessageDialog(v.getComponent(),
t.getMessage(),
null,
JOptionPane.ERROR_MESSAGE);
getDrawing().remove(createdFigure);
fireToolDone();
}
@Override
protected void finished() {
}
};
} else {
prototype = imagePrototype;
final ImageHolderFigure loaderFigure = ((ImageHolderFigure) prototype.clone());
worker = new Worker() {
@Override
protected Object construct() throws IOException {
((ImageHolderFigure) loaderFigure).loadImage(file);
return null;
}
@Override
protected void done(Object value) {
try {
if (createdFigure == null) {
((ImageHolderFigure) prototype).setImage(loaderFigure.getImageData(), loaderFigure.getBufferedImage());
} else {
((ImageHolderFigure) createdFigure).setImage(loaderFigure.getImageData(), loaderFigure.getBufferedImage());
}
} catch (IOException ex) {
JOptionPane.showMessageDialog(v.getComponent(),
ex.getMessage(),
null,
JOptionPane.ERROR_MESSAGE);
}
}
@Override
protected void failed(Throwable t) {
JOptionPane.showMessageDialog(v.getComponent(),
t.getMessage(),
null,
JOptionPane.ERROR_MESSAGE);
getDrawing().remove(createdFigure);
fireToolDone();
}
};
}
workerThread = new Thread(worker);
workerThread.start();
} else {
//getDrawing().remove(createdFigure);
if (isToolDoneAfterCreation()) {
fireToolDone();
}
}
}
// in java/org/jhotdraw/samples/svg/SVGCreateFromFileTool.java
Override
public Drawing construct() throws IOException {
Drawing drawing = new DefaultDrawing();
InputFormat in = (file.getName().toLowerCase().endsWith(".svg")) ? new SVGInputFormat() : new SVGZInputFormat();
in.read(file.toURI(), drawing);
return drawing;
}
// in java/org/jhotdraw/samples/svg/SVGCreateFromFileTool.java
Override
protected Object construct() throws IOException {
((ImageHolderFigure) loaderFigure).loadImage(file);
return null;
}
// in java/org/jhotdraw/samples/svg/SVGView.java
Override
public void write(URI uri, URIChooser chooser) throws IOException {
new SVGOutputFormat().write(new File(uri), svgPanel.getDrawing());
}
// in java/org/jhotdraw/samples/svg/SVGDrawingPanel.java
public void read(URI f) throws IOException {
// Create a new drawing object
Drawing newDrawing = createDrawing();
if (newDrawing.getInputFormats().size() == 0) {
throw new InternalError("Drawing object has no input formats.");
}
// Try out all input formats until we succeed
IOException firstIOException = null;
for (InputFormat format : newDrawing.getInputFormats()) {
try {
format.read(f, newDrawing);
final Drawing loadedDrawing = newDrawing;
Runnable r = new Runnable() {
@Override
public void run() {
// Set the drawing on the Event Dispatcher Thread
setDrawing(loadedDrawing);
}
};
if (SwingUtilities.isEventDispatchThread()) {
r.run();
} else {
try {
SwingUtilities.invokeAndWait(r);
} catch (InterruptedException ex) {
// suppress silently
} catch (InvocationTargetException ex) {
InternalError ie = new InternalError("Error setting drawing.");
ie.initCause(ex);
throw ie;
}
}
// We get here if reading was successful.
// We can return since we are done.
return;
//
} catch (IOException e) {
// We get here if reading failed.
// We only preserve the exception of the first input format,
// because that's the one which is best suited for this drawing.
if (firstIOException == null) {
firstIOException = e;
}
}
}
throw firstIOException;
}
// in java/org/jhotdraw/samples/svg/SVGDrawingPanel.java
public void read(URI f, InputFormat format) throws IOException {
if (format == null) {
read(f);
return;
}
// Create a new drawing object
Drawing newDrawing = createDrawing();
if (newDrawing.getInputFormats().size() == 0) {
throw new InternalError("Drawing object has no input formats.");
}
format.read(f, newDrawing);
final Drawing loadedDrawing = newDrawing;
Runnable r = new Runnable() {
@Override
public void run() {
// Set the drawing on the Event Dispatcher Thread
setDrawing(loadedDrawing);
}
};
if (SwingUtilities.isEventDispatchThread()) {
r.run();
} else {
try {
SwingUtilities.invokeAndWait(r);
} catch (InterruptedException ex) {
// suppress silently
} catch (InvocationTargetException ex) {
InternalError ie = new InternalError("Error setting drawing.");
ie.initCause(ex);
throw ie;
}
}
}
// in java/org/jhotdraw/samples/svg/SVGDrawingPanel.java
public void write(URI uri) throws IOException {
// Defensively clone the drawing object, so that we are not
// affected by changes of the drawing while we write it into the file.
final Drawing[] helper = new Drawing[1];
Runnable r = new Runnable() {
@Override
public void run() {
helper[0] = (Drawing) getDrawing().clone();
}
};
if (SwingUtilities.isEventDispatchThread()) {
r.run();
} else {
try {
SwingUtilities.invokeAndWait(r);
} catch (InterruptedException ex) {
// suppress silently
} catch (InvocationTargetException ex) {
InternalError ie = new InternalError("Error getting drawing.");
ie.initCause(ex);
throw ie;
}
}
Drawing saveDrawing = helper[0];
if (saveDrawing.getOutputFormats().size() == 0) {
throw new InternalError("Drawing object has no output formats.");
}
// Try out all output formats until we find one which accepts the
// filename entered by the user.
File f = new File(uri);
for (OutputFormat format : saveDrawing.getOutputFormats()) {
if (format.getFileFilter().accept(f)) {
format.write(uri, saveDrawing);
// We get here if writing was successful.
// We can return since we are done.
return;
}
}
throw new IOException("No output format for " + f.getName());
}
// in java/org/jhotdraw/samples/svg/SVGDrawingPanel.java
public void write(URI f, OutputFormat format) throws IOException {
if (format == null) {
write(f);
return;
}
// Defensively clone the drawing object, so that we are not
// affected by changes of the drawing while we write it into the file.
final Drawing[] helper = new Drawing[1];
Runnable r = new Runnable() {
@Override
public void run() {
helper[0] = (Drawing) getDrawing().clone();
}
};
if (SwingUtilities.isEventDispatchThread()) {
r.run();
} else {
try {
SwingUtilities.invokeAndWait(r);
} catch (InterruptedException ex) {
// suppress silently
} catch (InvocationTargetException ex) {
InternalError ie = new InternalError("Error getting drawing.");
ie.initCause(ex);
throw ie;
}
}
// Write drawing to file
Drawing saveDrawing = helper[0];
format.write(f, saveDrawing);
}
// in java/org/jhotdraw/samples/draw/DrawApplet.java
Override
public void init() {
// Set look and feel
// -----------------
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Throwable e) {
// Do nothing.
// If we can't set the desired look and feel, UIManager does
// automaticaly the right thing for us.
}
// Set our own popup factory, because the one that comes with Mac OS X
// creates translucent popups which is not useful for color selection
// using pop menus.
try {
PopupFactory.setSharedInstance(new PopupFactory());
} catch (Throwable e) {
// If we can't set the popup factory, we have to use what is there.
}
// Display copyright info while we are loading the data
// ----------------------------------------------------
Container c = getContentPane();
c.setLayout(new BoxLayout(c, BoxLayout.Y_AXIS));
String[] labels = getAppletInfo().split("\n");//Strings.split(getAppletInfo(), '\n');
for (int i = 0; i < labels.length; i++) {
c.add(new JLabel((labels[i].length() == 0) ? " " : labels[i]));
}
// We load the data using a worker thread
// --------------------------------------
new Worker<Drawing>() {
@Override
protected Drawing construct() throws IOException {
Drawing result;
if (getParameter("data") != null) {
NanoXMLDOMInput domi = new NanoXMLDOMInput(new DrawFigureFactory(), new StringReader(getParameter("data")));
result = (Drawing) domi.readObject(0);
} else if (getParameter("datafile") != null) {
URL url = new URL(getDocumentBase(), getParameter("datafile"));
InputStream in = url.openConnection().getInputStream();
try {
NanoXMLDOMInput domi = new NanoXMLDOMInput(new DrawFigureFactory(), in);
result = (Drawing) domi.readObject(0);
} finally {
in.close();
}
} else {
result = null;
}
return result;
}
@Override
protected void done(Drawing result) {
Container c = getContentPane();
c.setLayout(new BorderLayout());
c.removeAll();
c.add(drawingPanel = new DrawingPanel());
initComponents();
if (result != null) {
setDrawing(result);
}
}
@Override
protected void failed(Throwable result) {
Container c = getContentPane();
c.setLayout(new BorderLayout());
c.removeAll();
c.add(drawingPanel = new DrawingPanel());
result.printStackTrace();
getDrawing().add(new TextFigure(result.toString()));
result.printStackTrace();
}
@Override
protected void finished() {
Container c = getContentPane();
initDrawing(getDrawing());
c.validate();
}
}.start();
}
// in java/org/jhotdraw/samples/draw/DrawApplet.java
Override
protected Drawing construct() throws IOException {
Drawing result;
if (getParameter("data") != null) {
NanoXMLDOMInput domi = new NanoXMLDOMInput(new DrawFigureFactory(), new StringReader(getParameter("data")));
result = (Drawing) domi.readObject(0);
} else if (getParameter("datafile") != null) {
URL url = new URL(getDocumentBase(), getParameter("datafile"));
InputStream in = url.openConnection().getInputStream();
try {
NanoXMLDOMInput domi = new NanoXMLDOMInput(new DrawFigureFactory(), in);
result = (Drawing) domi.readObject(0);
} finally {
in.close();
}
} else {
result = null;
}
return result;
}
// in java/org/jhotdraw/samples/draw/DrawLiveConnectApplet.java
Override
public void init() {
// Set look and feel
// -----------------
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Throwable e) {
// Do nothing.
// If we can't set the desired look and feel, UIManager does
// automaticaly the right thing for us.
}
// Display copyright info while we are loading the data
// ----------------------------------------------------
Container c = getContentPane();
c.setLayout(new BoxLayout(c, BoxLayout.Y_AXIS));
String[] lines = getAppletInfo().split("\n");//Strings.split(getAppletInfo(), '\n');
for (int i = 0; i < lines.length; i++) {
c.add(new JLabel(lines[i]));
}
// We load the data using a worker thread
// --------------------------------------
new Worker<Drawing>() {
@Override
protected Drawing construct() throws IOException {
Drawing result;
if (getParameter("data") != null && getParameter("data").length() > 0) {
NanoXMLDOMInput domi = new NanoXMLDOMInput(new DrawFigureFactory(), new StringReader(getParameter("data")));
result = (Drawing) domi.readObject(0);
} else if (getParameter("datafile") != null) {
InputStream in = null;
try {
URL url = new URL(getDocumentBase(), getParameter("datafile"));
in = url.openConnection().getInputStream();
NanoXMLDOMInput domi = new NanoXMLDOMInput(new DrawFigureFactory(), in);
result = (Drawing) domi.readObject(0);
} finally {
if (in != null) {
in.close();
}
}
} else {
result = null;
}
return result;
}
@Override
protected void done(Drawing result) {
Container c = getContentPane();
c.setLayout(new BorderLayout());
c.removeAll();
initComponents();
if (result != null) {
setDrawing(result);
}
}
@Override
protected void failed(Throwable result) {
Container c = getContentPane();
c.setLayout(new BorderLayout());
c.removeAll();
initComponents();
getDrawing().add(new TextFigure(result.toString()));
result.printStackTrace();
}
@Override
protected void finished() {
Container c = getContentPane();
boolean isLiveConnect;
try {
Class.forName("netscape.javascript.JSObject");
isLiveConnect = true;
} catch (Throwable t) {
isLiveConnect = false;
}
loadButton.setEnabled(isLiveConnect && getParameter("dataread") != null);
saveButton.setEnabled(isLiveConnect && getParameter("datawrite") != null);
if (isLiveConnect) {
String methodName = getParameter("dataread");
if (methodName.indexOf('(') > 0) {
methodName = methodName.substring(0, methodName.indexOf('(') - 1);
}
JSObject win = JSObject.getWindow(DrawLiveConnectApplet.this);
Object data = win.call(methodName, new Object[0]);
if (data instanceof String) {
setData((String) data);
}
}
c.validate();
}
}.start();
}
// in java/org/jhotdraw/samples/draw/DrawLiveConnectApplet.java
Override
protected Drawing construct() throws IOException {
Drawing result;
if (getParameter("data") != null && getParameter("data").length() > 0) {
NanoXMLDOMInput domi = new NanoXMLDOMInput(new DrawFigureFactory(), new StringReader(getParameter("data")));
result = (Drawing) domi.readObject(0);
} else if (getParameter("datafile") != null) {
InputStream in = null;
try {
URL url = new URL(getDocumentBase(), getParameter("datafile"));
in = url.openConnection().getInputStream();
NanoXMLDOMInput domi = new NanoXMLDOMInput(new DrawFigureFactory(), in);
result = (Drawing) domi.readObject(0);
} finally {
if (in != null) {
in.close();
}
}
} else {
result = null;
}
return result;
}
// in java/org/jhotdraw/samples/draw/DrawView.java
Override
public void write(URI f, URIChooser fc) throws IOException {
Drawing drawing = view.getDrawing();
OutputFormat outputFormat = drawing.getOutputFormats().get(0);
outputFormat.write(f, drawing);
}
// in java/org/jhotdraw/samples/draw/DrawView.java
Override
public void read(URI f, URIChooser fc) throws IOException {
try {
final Drawing drawing = createDrawing();
boolean success = false;
for (InputFormat sfi : drawing.getInputFormats()) {
try {
sfi.read(f, drawing, true);
success = true;
break;
} catch (Exception e) {
// try with the next input format
}
}
if (!success) {
ResourceBundleUtil labels = ResourceBundleUtil.getBundle("org.jhotdraw.app.Labels");
throw new IOException(labels.getFormatted("file.open.unsupportedFileFormat.message", URIUtil.getName(f)));
}
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
view.getDrawing().removeUndoableEditListener(undo);
view.setDrawing(drawing);
view.getDrawing().addUndoableEditListener(undo);
undo.discardAllEdits();
}
});
} catch (InterruptedException e) {
InternalError error = new InternalError();
e.initCause(e);
throw error;
} catch (InvocationTargetException e) {
InternalError error = new InternalError();
error.initCause(e);
throw error;
}
}
// in java/org/jhotdraw/samples/odg/io/ODGInputFormat.java
Override
public void read(URI uri, Drawing drawing) throws IOException {
read(new File(uri), drawing);
}
// in java/org/jhotdraw/samples/odg/io/ODGInputFormat.java
Override
public void read(URI uri, Drawing drawing, boolean replace) throws IOException {
read(new File(uri), drawing, replace);
}
// in java/org/jhotdraw/samples/odg/io/ODGInputFormat.java
public void read(File file, Drawing drawing) throws IOException {
read(file, drawing, true);
}
// in java/org/jhotdraw/samples/odg/io/ODGInputFormat.java
public void read(File file, Drawing drawing, boolean replace) throws IOException {
BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
try {
read(in, drawing, replace);
} finally {
in.close();
}
}
// in java/org/jhotdraw/samples/odg/io/ODGInputFormat.java
Override
public void read(Transferable t, Drawing drawing, boolean replace) throws UnsupportedFlavorException, IOException {
InputStream in = (InputStream) t.getTransferData(new DataFlavor("application/vnd.oasis.opendocument.graphics", "Image SVG"));
try {
read(in, drawing, replace);
} finally {
in.close();
}
}
// in java/org/jhotdraw/samples/odg/io/ODGInputFormat.java
private byte[] readAllBytes(InputStream in) throws IOException {
ByteArrayOutputStream tmp = new ByteArrayOutputStream();
byte[] buf = new byte[512];
for (int len; -1 != (len = in.read(buf));) {
tmp.write(buf, 0, len);
}
tmp.close();
return tmp.toByteArray();
}
// in java/org/jhotdraw/samples/odg/io/ODGInputFormat.java
Override
public void read(InputStream in, Drawing drawing, boolean replace) throws IOException {
// Read the file into a byte array.
byte[] tmp = readAllBytes(in);
// Input stream of the content.xml file
InputStream contentIn = null;
// Input stream of the styles.xml file
InputStream stylesIn = null;
// Try to read "tmp" as a ZIP-File.
boolean isZipped = true;
try {
ZipInputStream zin = new ZipInputStream(new ByteArrayInputStream(tmp));
for (ZipEntry entry; null != (entry = zin.getNextEntry());) {
if (entry.getName().equals("content.xml")) {
contentIn = new ByteArrayInputStream(
readAllBytes(zin));
} else if (entry.getName().equals("styles.xml")) {
stylesIn = new ByteArrayInputStream(
readAllBytes(zin));
}
}
} catch (ZipException e) {
isZipped = false;
}
if (contentIn == null) {
contentIn = new ByteArrayInputStream(tmp);
}
if (stylesIn == null) {
stylesIn = new ByteArrayInputStream(tmp);
}
styles = new ODGStylesReader();
styles.read(stylesIn);
readFiguresFromDocumentContent(contentIn, drawing, replace);
}
// in java/org/jhotdraw/samples/odg/io/ODGInputFormat.java
private void readDrawingElement(IXMLElement elem)
throws IOException {
/*
2.3.2Drawing Documents
The content of drawing document consists of a sequence of draw pages.
<define name="office-body-content" combine="choice">
<element name="office:drawing">
<ref name="office-drawing-attlist"/>
<ref name="office-drawing-content-prelude"/>
<ref name="office-drawing-content-main"/>
<ref name="office-drawing-content-epilogue"/>
</element>
</define>
<define name="office-drawing-attlist">
<empty/>
</define>
Drawing Document Content Model
The drawing document prelude may contain text declarations only. To allow office applications to
implement functionality that usually is available in spreadsheets for drawing documents, it may
also contain elements that implement enhanced table features. See also section 2.3.4.
<define name="office-drawing-content-prelude">
<ref name="text-decls"/>
<ref name="table-decls"/>
</define>
The main document content contains a sequence of draw pages.
<define name="office-drawing-content-main">
<zeroOrMore>
<ref name="draw-page"/>
</zeroOrMore>
</define>
There are no drawing documents specific epilogue elements, but the epilogue may contain
elements that implement enhanced table features. See also section 2.3.4.
<define name="office-drawing-content-epilogue">
<ref name="table-functions"/>
</define>
*/
for (IXMLElement child : elem.getChildren()) {
if (child.getNamespace() == null
|| child.getNamespace().equals(DRAWING_NAMESPACE)) {
String name = child.getName();
if (name.equals("page")) {
readPageElement(child);
}
}
}
}
// in java/org/jhotdraw/samples/odg/io/ODGInputFormat.java
private void readPageElement(IXMLElement elem)
throws IOException {
/* 9.1.4Drawing Pages
*
The element <draw:page> is a container for content in a drawing or presentation document.
Drawing pages are used for the following:
• Forms (see section 11.1)
• Drawings (see section 9.2)
• Frames (see section 9.3)
• Presentation Animations (see section 9.7)
• Presentation Notes (see section 9.1.5)
*
A master page must be assigned to each drawing page.
*
<define name="draw-page">
<element name="draw:page">
<ref name="common-presentation-header-footer-attlist"/>
<ref name="draw-page-attlist"/>
<optional>
<ref name="office-forms"/>
</optional>
<zeroOrMore>
<ref name="shape"/>
</zeroOrMore>
<optional>
<choice>
<ref name="presentation-animations"/>
<ref name="animation-element"/>
</choice>
</optional>
<optional>
<ref name="presentation-notes"/>
</optional>
</element>
</define>
*
The attributes that may be associated with the <draw:page> element are:
• Page name
• Page style
• Master page
• Presentation page layout
• Header declaration
• Footer declaration
• Date and time declaration
• ID
*
The elements that my be included in the <draw:page> element are:
• Forms
• Shapes
• Animations
• Presentation notes
*/
for (IXMLElement child : elem.getChildren()) {
ODGFigure figure = readElement(child);
if (figure != null) {
figures.add(figure);
}
}
}
// in java/org/jhotdraw/samples/odg/io/ODGInputFormat.java
Nullable
private ODGFigure readElement(IXMLElement elem)
throws IOException {
/*
Drawing Shapes
This section describes drawing shapes that might occur within all kind of applications.
<define name="shape">
<choice>
<ref name="draw-rect"/>
<ref name="draw-line"/>
<ref name="draw-polyline"/>
<ref name="draw-polygon"/>
<ref name="draw-regular-polygon"/>
<ref name="draw-path"/>
<ref name="draw-circle"/>
<ref name="draw-ellipse"/>
<ref name="draw-g"/>
<ref name="draw-page-thumbnail"/>
<ref name="draw-frame"/>
<ref name="draw-measure"/>
<ref name="draw-caption"/>
<ref name="draw-connector"/>
<ref name="draw-control"/>
<ref name="dr3d-scene"/>
<ref name="draw-custom-shape"/>
</choice>
</define>
*/
ODGFigure f = null;
if (elem.getNamespace() == null
|| elem.getNamespace().equals(DRAWING_NAMESPACE)) {
String name = elem.getName();
if (name.equals("caption")) {
f = readCaptionElement(elem);
} else if (name.equals("circle")) {
f = readCircleElement(elem);
} else if (name.equals("connector")) {
f = readCircleElement(elem);
} else if (name.equals("custom-shape")) {
f = readCustomShapeElement(elem);
} else if (name.equals("ellipse")) {
f = readEllipseElement(elem);
} else if (name.equals("frame")) {
f = readFrameElement(elem);
} else if (name.equals("g")) {
f = readGElement(elem);
} else if (name.equals("line")) {
f = readLineElement(elem);
} else if (name.equals("measure")) {
f = readMeasureElement(elem);
} else if (name.equals("path")) {
f = readPathElement(elem);
} else if (name.equals("polygon")) {
f = readPolygonElement(elem);
} else if (name.equals("polyline")) {
f = readPolylineElement(elem);
} else if (name.equals("rect")) {
f = readRectElement(elem);
} else if (name.equals("regularPolygon")) {
f = readRegularPolygonElement(elem);
} else {
if (DEBUG) {
System.out.println("ODGInputFormat.readElement(" + elem + ") not implemented.");
}
}
}
if (f != null) {
if (f.isEmpty()) {
if (DEBUG) {
System.out.println("ODGInputFormat.readElement():null - discarded empty figure " + f);
}
return null;
}
if (DEBUG) {
System.out.println("ODGInputFormat.readElement():" + f + ".");
}
}
return f;
}
// in java/org/jhotdraw/samples/odg/io/ODGInputFormat.java
private ODGFigure readEllipseElement(IXMLElement elem)
throws IOException {
throw new UnsupportedOperationException("not implemented");
}
// in java/org/jhotdraw/samples/odg/io/ODGInputFormat.java
private ODGFigure readCircleElement(IXMLElement elem)
throws IOException {
throw new UnsupportedOperationException("not implemented");
}
// in java/org/jhotdraw/samples/odg/io/ODGInputFormat.java
private ODGFigure readCustomShapeElement(IXMLElement elem)
throws IOException {
String styleName = elem.getAttribute("style-name", DRAWING_NAMESPACE, null);
Map<AttributeKey, Object> a = styles.getAttributes(styleName, "graphic");
Rectangle2D.Double figureBounds = new Rectangle2D.Double(
toLength(elem.getAttribute("x", SVG_NAMESPACE, "0"), 1),
toLength(elem.getAttribute("y", SVG_NAMESPACE, "0"), 1),
toLength(elem.getAttribute("width", SVG_NAMESPACE, "0"), 1),
toLength(elem.getAttribute("height", SVG_NAMESPACE, "0"), 1));
ODGFigure figure = null;
for (IXMLElement child : elem.getChildrenNamed("enhanced-geometry", DRAWING_NAMESPACE)) {
figure = readEnhancedGeometryElement(child, a, figureBounds);
}
return figure;
}
// in java/org/jhotdraw/samples/odg/io/ODGInputFormat.java
Nullable
private ODGFigure readEnhancedGeometryElement(
IXMLElement elem,
Map<AttributeKey, Object> a,
Rectangle2D.Double figureBounds)
throws IOException {
/* The <draw:enhanced-geometry> element contains the geometry for a
* <draw:custom-shape> element if its draw:engine attribute has been
* omitted.
*/
/* The draw:type attribute contains the name of a shape type. This name
* can be used to offer specialized user interfaces for certain classes
* of shapes, like for arrows, smileys, etc.
* The shape type is rendering engine dependent and does not influence
* the geometry of the shape.
* If the value of the draw:type attribute is non-primitive, then no
* shape type is available.
*/
String type = elem.getAttribute("type", DRAWING_NAMESPACE, "non-primitive");
EnhancedPath path;
if (elem.hasAttribute("enhanced-path", DRAWING_NAMESPACE)) {
path = toEnhancedPath(
elem.getAttribute("enhanced-path", DRAWING_NAMESPACE, null));
} else {
path = null;
}
/* The svg:viewBox attribute establishes a user coordinate system inside
* the physical coordinate system of the shape specified by the position
* and size attributes. This user coordinate system is used by the
* <draw:enhanced-path> element.
* The syntax for using this attribute is the same as the [SVG] syntax.
* The value of the attribute are four numbers separated by white
* spaces, which define the left, top, right, and bottom dimensions
* of the user coordinate system.
*/
String[] viewBoxValues = toWSOrCommaSeparatedArray(
elem.getAttribute("viewBox", DRAWING_NAMESPACE, "0 0 100 100"));
Rectangle2D.Double viewBox = new Rectangle2D.Double(
toNumber(viewBoxValues[0]),
toNumber(viewBoxValues[1]),
toNumber(viewBoxValues[2]),
toNumber(viewBoxValues[3]));
AffineTransform viewTx = new AffineTransform();
if (!viewBox.isEmpty()) {
viewTx.scale(figureBounds.width / viewBox.width, figureBounds.height / viewBox.height);
viewTx.translate(figureBounds.x - viewBox.x, figureBounds.y - viewBox.y);
}
/* The draw:mirror-vertical and draw:mirror-horizontal attributes
* specify if the geometry of the shape is to be mirrored.
*/
boolean mirrorVertical = elem.getAttribute("mirror-vertical", DRAWING_NAMESPACE, "false").equals("true");
boolean mirrorHorizontal = elem.getAttribute("mirror-horizontal", DRAWING_NAMESPACE, "false").equals("true");
// FIXME - Implement Text Rotate Angle
// FIXME - Implement Extrusion Allowed
// FIXME - Implement Text Path Allowed
// FIXME - Implement Concentric Gradient Allowed
ODGFigure figure;
if (type.equals("rectangle")) {
figure = createEnhancedGeometryRectangleFigure(figureBounds, a);
} else if (type.equals("ellipse")) {
figure = createEnhancedGeometryEllipseFigure(figureBounds, a);
} else {
System.out.println("ODGInputFormat.readEnhancedGeometryElement not implemented for " + elem);
figure = null;
}
return figure;
}
// in java/org/jhotdraw/samples/odg/io/ODGInputFormat.java
private ODGFigure createEnhancedGeometryEllipseFigure(
Rectangle2D.Double bounds, Map<AttributeKey, Object> a)
throws IOException {
ODGEllipseFigure figure = new ODGEllipseFigure();
figure.setBounds(bounds);
figure.setAttributes(a);
return figure;
}
// in java/org/jhotdraw/samples/odg/io/ODGInputFormat.java
private ODGFigure createEnhancedGeometryRectangleFigure(
Rectangle2D.Double bounds, Map<AttributeKey, Object> a)
throws IOException {
ODGRectFigure figure = new ODGRectFigure();
figure.setBounds(bounds);
figure.setAttributes(a);
return figure;
}
// in java/org/jhotdraw/samples/odg/io/ODGInputFormat.java
private ODGFigure createLineFigure(
Point2D.Double p1, Point2D.Double p2,
Map<AttributeKey, Object> a)
throws IOException {
ODGPathFigure figure = new ODGPathFigure();
figure.setBounds(p1, p2);
figure.setAttributes(a);
return figure;
}
// in java/org/jhotdraw/samples/odg/io/ODGInputFormat.java
private ODGFigure createPolylineFigure(
Point2D.Double[] points,
Map<AttributeKey, Object> a)
throws IOException {
ODGPathFigure figure = new ODGPathFigure();
ODGBezierFigure bezier = new ODGBezierFigure();
for (Point2D.Double p : points) {
bezier.addNode(new BezierPath.Node(p.x, p.y));
}
figure.removeAllChildren();
figure.add(bezier);
figure.setAttributes(a);
return figure;
}
// in java/org/jhotdraw/samples/odg/io/ODGInputFormat.java
private ODGFigure createPolygonFigure(
Point2D.Double[] points,
Map<AttributeKey, Object> a)
throws IOException {
ODGPathFigure figure = new ODGPathFigure();
ODGBezierFigure bezier = new ODGBezierFigure();
for (Point2D.Double p : points) {
bezier.addNode(new BezierPath.Node(p.x, p.y));
}
bezier.setClosed(true);
figure.removeAllChildren();
figure.add(bezier);
figure.setAttributes(a);
return figure;
}
// in java/org/jhotdraw/samples/odg/io/ODGInputFormat.java
private ODGFigure createPathFigure(
BezierPath[] paths,
Map<AttributeKey, Object> a)
throws IOException {
ODGPathFigure figure = new ODGPathFigure();
figure.removeAllChildren();
for (BezierPath p : paths) {
ODGBezierFigure bezier = new ODGBezierFigure();
bezier.setBezierPath(p);
figure.add(bezier);
}
figure.setAttributes(a);
return figure;
}
// in java/org/jhotdraw/samples/odg/io/ODGInputFormat.java
private ODGFigure readFrameElement(IXMLElement elem) throws IOException {
throw new UnsupportedOperationException("not implemented.");
}
// in java/org/jhotdraw/samples/odg/io/ODGInputFormat.java
private CompositeFigure createGroupFigure()
throws IOException {
ODGGroupFigure figure = new ODGGroupFigure();
return figure;
}
// in java/org/jhotdraw/samples/odg/io/ODGInputFormat.java
private ODGFigure readGElement(IXMLElement elem)
throws IOException {
CompositeFigure g = createGroupFigure();
for (IXMLElement child : elem.getChildren()) {
Figure childFigure = readElement(child);
if (childFigure != null) {
g.basicAdd(childFigure);
}
}
/*
readTransformAttribute(elem, a);
if (TRANSFORM.get(a) != null) {
g.transform(TRANSFORM.get(a));
}*/
return (ODGFigure) g;
}
// in java/org/jhotdraw/samples/odg/io/ODGInputFormat.java
private ODGFigure readLineElement(IXMLElement elem)
throws IOException {
Point2D.Double p1 = new Point2D.Double(
toLength(elem.getAttribute("x1", SVG_NAMESPACE, "0"), 1),
toLength(elem.getAttribute("y1", SVG_NAMESPACE, "0"), 1));
Point2D.Double p2 = new Point2D.Double(
toLength(elem.getAttribute("x2", SVG_NAMESPACE, "0"), 1),
toLength(elem.getAttribute("y2", SVG_NAMESPACE, "0"), 1));
String styleName = elem.getAttribute("style-name", DRAWING_NAMESPACE, null);
Map<AttributeKey, Object> a = styles.getAttributes(styleName, "graphic");
ODGFigure f = createLineFigure(p1, p2, a);
return f;
}
// in java/org/jhotdraw/samples/odg/io/ODGInputFormat.java
private ODGFigure readPathElement(IXMLElement elem)
throws IOException {
AffineTransform viewBoxTransform = readViewBoxTransform(elem);
BezierPath[] paths = toPath(elem.getAttribute("d", SVG_NAMESPACE, null));
for (BezierPath p : paths) {
p.transform(viewBoxTransform);
}
String styleName = elem.getAttribute("style-name", DRAWING_NAMESPACE, null);
HashMap<AttributeKey, Object> a = new HashMap<AttributeKey, Object>();
a.putAll(styles.getAttributes(styleName, "graphic"));
readCommonDrawingShapeAttributes(elem, a);
ODGFigure f = createPathFigure(paths, a);
return f;
}
// in java/org/jhotdraw/samples/odg/io/ODGInputFormat.java
private ODGFigure readPolygonElement(IXMLElement elem)
throws IOException {
AffineTransform viewBoxTransform = readViewBoxTransform(elem);
String[] coords = toWSOrCommaSeparatedArray(elem.getAttribute("points", DRAWING_NAMESPACE, null));
Point2D.Double[] points = new Point2D.Double[coords.length / 2];
for (int i = 0; i < coords.length; i += 2) {
Point2D.Double p = new Point2D.Double(toNumber(coords[i]), toNumber(coords[i + 1]));
points[i / 2] = (Point2D.Double) viewBoxTransform.transform(p, p);
}
String styleName = elem.getAttribute("style-name", DRAWING_NAMESPACE, null);
HashMap<AttributeKey, Object> a = new HashMap<AttributeKey, Object>();
a.putAll(styles.getAttributes(styleName, "graphic"));
readCommonDrawingShapeAttributes(elem, a);
ODGFigure f = createPolygonFigure(points, a);
return f;
}
// in java/org/jhotdraw/samples/odg/io/ODGInputFormat.java
private ODGFigure readPolylineElement(IXMLElement elem)
throws IOException {
AffineTransform viewBoxTransform = readViewBoxTransform(elem);
String[] coords = toWSOrCommaSeparatedArray(elem.getAttribute("points", DRAWING_NAMESPACE, null));
Point2D.Double[] points = new Point2D.Double[coords.length / 2];
for (int i = 0; i < coords.length; i += 2) {
Point2D.Double p = new Point2D.Double(toNumber(coords[i]), toNumber(coords[i + 1]));
points[i / 2] = (Point2D.Double) viewBoxTransform.transform(p, p);
}
String styleName = elem.getAttribute("style-name", DRAWING_NAMESPACE, null);
HashMap<AttributeKey, Object> a = new HashMap<AttributeKey, Object>();
a.putAll(styles.getAttributes(styleName, "graphic"));
readCommonDrawingShapeAttributes(elem, a);
ODGFigure f = createPolylineFigure(points, a);
return f;
}
// in java/org/jhotdraw/samples/odg/io/ODGInputFormat.java
private ODGFigure readRectElement(IXMLElement elem)
throws IOException {
throw new UnsupportedOperationException("ODGInputFormat.readRectElement(" + elem + "):null - not implemented");
}
// in java/org/jhotdraw/samples/odg/io/ODGInputFormat.java
private ODGFigure readRegularPolygonElement(IXMLElement elem)
throws IOException {
throw new UnsupportedOperationException("ODGInputFormat.readRegularPolygonElement(" + elem + "):null - not implemented");
}
// in java/org/jhotdraw/samples/odg/io/ODGInputFormat.java
private ODGFigure readMeasureElement(IXMLElement elem)
throws IOException {
throw new UnsupportedOperationException("ODGInputFormat.readMeasureElement(" + elem + "):null - not implemented");
}
// in java/org/jhotdraw/samples/odg/io/ODGInputFormat.java
private ODGFigure readCaptionElement(IXMLElement elem)
throws IOException {
throw new UnsupportedOperationException("ODGInputFormat.readCaptureElement(" + elem + "):null - not implemented");
}
// in java/org/jhotdraw/samples/odg/io/ODGInputFormat.java
public static String[] toWSOrCommaSeparatedArray(String str) throws IOException {
String[] result = str.split("(\\s*,\\s*|\\s+)");
if (result.length == 1 && result[0].equals("")) {
return new String[0];
} else {
return result;
}
}
// in java/org/jhotdraw/samples/odg/io/ODGInputFormat.java
private double toNumber(String str) throws IOException {
return toLength(str, 100);
}
// in java/org/jhotdraw/samples/odg/io/ODGInputFormat.java
private double toLength(String str, double percentFactor) throws IOException {
double scaleFactor = 1d;
if (str == null || str.length() == 0) {
return 0d;
}
if (str.endsWith("%")) {
str = str.substring(0, str.length() - 1);
scaleFactor = percentFactor;
} else if (str.endsWith("px")) {
str = str.substring(0, str.length() - 2);
} else if (str.endsWith("pt")) {
str = str.substring(0, str.length() - 2);
scaleFactor = 1.25;
} else if (str.endsWith("pc")) {
str = str.substring(0, str.length() - 2);
scaleFactor = 15;
} else if (str.endsWith("mm")) {
str = str.substring(0, str.length() - 2);
scaleFactor = 3.543307;
} else if (str.endsWith("cm")) {
str = str.substring(0, str.length() - 2);
scaleFactor = 35.43307;
} else if (str.endsWith("in")) {
str = str.substring(0, str.length() - 2);
scaleFactor = 90;
} else {
scaleFactor = 1d;
}
return Double.parseDouble(str) * scaleFactor;
}
// in java/org/jhotdraw/samples/odg/io/ODGInputFormat.java
private static double toUnitFactor(String str) throws IOException {
double scaleFactor;
if (str.equals("px")) {
scaleFactor = 1d;
} else if (str.endsWith("pt")) {
scaleFactor = 1.25;
} else if (str.endsWith("pc")) {
scaleFactor = 15;
} else if (str.endsWith("mm")) {
scaleFactor = 3.543307;
} else if (str.endsWith("cm")) {
scaleFactor = 35.43307;
} else if (str.endsWith("in")) {
scaleFactor = 90;
} else {
scaleFactor = 1d;
}
return scaleFactor;
}
// in java/org/jhotdraw/samples/odg/io/ODGInputFormat.java
private EnhancedPath toEnhancedPath(String str) throws IOException {
if (DEBUG) {
System.out.println("ODGInputFormat toEnhancedPath " + str);
}
EnhancedPath path = null;
Object x, y;
Object x1, y1, x2, y2, x3, y3;
StreamPosTokenizer tt = new StreamPosTokenizer(new StringReader(str));
tt.resetSyntax();
tt.parseNumbers();
tt.parseExponents();
tt.parsePlusAsNumber();
tt.whitespaceChars(0, ' ');
tt.whitespaceChars(',', ',');
char nextCommand = 'M';
char command = 'M';
Commands:
while (tt.nextToken() != StreamPosTokenizer.TT_EOF) {
if (tt.ttype > 0) {
command = (char) tt.ttype;
} else {
command = nextCommand;
tt.pushBack();
}
nextCommand = command;
switch (command) {
case 'M':
// moveto (x y)+
// Start a new sub-path at the given (x,y)
// coordinate. If a moveto is followed by multiple
// pairs of coordinates, they are treated as lineto.
if (path == null) {
path = new EnhancedPath();
}
// path.setFilled(isFilled);
//path.setStroked(isStroked);
x = nextEnhancedCoordinate(tt, str);
y = nextEnhancedCoordinate(tt, str);
path.moveTo(x, y);
nextCommand = 'L';
break;
case 'L':
// lineto (x y)+
// Draws a line from the current point to (x, y). If
// multiple coordinate pairs are following, they
// are all interpreted as lineto.
x = nextEnhancedCoordinate(tt, str);
y = nextEnhancedCoordinate(tt, str);
path.lineTo(x, y);
break;
case 'C':
// curveto (x1 y1 x2 y2 x y)+
// Draws a cubic BeÌzier curve from the current
// point to (x,y) using (x1,y1) as the control point
// at the beginning of the curve and (x2,y2) as
// the control point at the end of the curve.
x1 = nextEnhancedCoordinate(tt, str);
y1 = nextEnhancedCoordinate(tt, str);
x2 = nextEnhancedCoordinate(tt, str);
y2 = nextEnhancedCoordinate(tt, str);
x = nextEnhancedCoordinate(tt, str);
y = nextEnhancedCoordinate(tt, str);
path.curveTo(x1, y1, x2, y2, x, y);
break;
case 'Z':
// closepath
// Close the current sub-path by drawing a
// straight line from the current point to current
// sub-path's initial point.
path.close();
break;
case 'N':
// endpath
// Ends the current put of sub-paths. The sub-
// paths will be filled by using the “even-oddâ€
// filling rule. Other following subpaths will be
// filled independently.
break;
case 'F':
// nofill
// Specifies that the current put of sub-paths
// won't be filled.
break;
case 'S':
// nostroke
// Specifies that the current put of sub-paths
// won't be stroked.
break;
case 'T':
// angle-ellipseto (x y w h t0 t1) +
// Draws a segment of an ellipse. The ellipse is specified
// by the center(x, y), the size(w, h) and the start-angle
// t0 and end-angle t1.
x = nextEnhancedCoordinate(tt, str);
y = nextEnhancedCoordinate(tt, str);
x1 = nextEnhancedCoordinate(tt, str);
y1 = nextEnhancedCoordinate(tt, str);
x2 = nextEnhancedCoordinate(tt, str);
y2 = nextEnhancedCoordinate(tt, str);
path.ellipseTo(x, y, x1, y1, x2, y2);
break;
case 'U':
// angle-ellipse (x y w h t0 t1) +
// The same as the “T†command, except that a implied moveto
// to the starting point is done.
x = nextEnhancedCoordinate(tt, str);
y = nextEnhancedCoordinate(tt, str);
x1 = nextEnhancedCoordinate(tt, str);
y1 = nextEnhancedCoordinate(tt, str);
x2 = nextEnhancedCoordinate(tt, str);
y2 = nextEnhancedCoordinate(tt, str);
path.moveTo(x1, y1);
path.ellipseTo(x, y, x1, y1, x2, y2);
break;
case 'A':
// arcto (x1 y1 x2 y2 x3 y3 x y) +
// (x1, y1) and (x2, y2) is defining the bounding
// box of a ellipse. A line is then drawn from the
// current point to the start angle of the arc that is
// specified by the radial vector of point (x3, y3)
// and then counter clockwise to the end-angle
// that is specified by point (x4, y4).
x1 = nextEnhancedCoordinate(tt, str);
y1 = nextEnhancedCoordinate(tt, str);
x2 = nextEnhancedCoordinate(tt, str);
y2 = nextEnhancedCoordinate(tt, str);
x3 = nextEnhancedCoordinate(tt, str);
y3 = nextEnhancedCoordinate(tt, str);
x = nextEnhancedCoordinate(tt, str);
y = nextEnhancedCoordinate(tt, str);
path.arcTo(x1, y1, x2, y2, x3, y3, x, y);
break;
case 'B':
// arc (x1 y1 x2 y2 x3 y3 x y) +
// The same as the “A†command, except that a
// implied moveto to the starting point is done.
x1 = nextEnhancedCoordinate(tt, str);
y1 = nextEnhancedCoordinate(tt, str);
x2 = nextEnhancedCoordinate(tt, str);
y2 = nextEnhancedCoordinate(tt, str);
x3 = nextEnhancedCoordinate(tt, str);
y3 = nextEnhancedCoordinate(tt, str);
x = nextEnhancedCoordinate(tt, str);
y = nextEnhancedCoordinate(tt, str);
path.moveTo(x1, y1);
path.arcTo(x1, y1, x2, y2, x3, y3, x, y);
break;
case 'W':
// clockwisearcto (x1 y1 x2 y2 x3 y3 x y) +
// The same as the “A†command except, that the arc is drawn
// clockwise.
x1 = nextEnhancedCoordinate(tt, str);
y1 = nextEnhancedCoordinate(tt, str);
x2 = nextEnhancedCoordinate(tt, str);
y2 = nextEnhancedCoordinate(tt, str);
x3 = nextEnhancedCoordinate(tt, str);
y3 = nextEnhancedCoordinate(tt, str);
x = nextEnhancedCoordinate(tt, str);
y = nextEnhancedCoordinate(tt, str);
path.clockwiseArcTo(x1, y1, x2, y2, x3, y3, x, y);
break;
case 'V':
// clockwisearc (x1 y1 x2 y2 x3 y3 x y)+
// The same as the “A†command, except that a implied moveto
// to the starting point is done and the arc is drawn
// clockwise.
x1 = nextEnhancedCoordinate(tt, str);
y1 = nextEnhancedCoordinate(tt, str);
x2 = nextEnhancedCoordinate(tt, str);
y2 = nextEnhancedCoordinate(tt, str);
x3 = nextEnhancedCoordinate(tt, str);
y3 = nextEnhancedCoordinate(tt, str);
x = nextEnhancedCoordinate(tt, str);
y = nextEnhancedCoordinate(tt, str);
path.moveTo(x1, y1);
path.clockwiseArcTo(x1, y1, x2, y2, x3, y3, x, y);
break;
case 'X':
// elliptical-quadrantx (x y) +
// Draws a quarter ellipse, whose initial segment is
// tangential to the x-axis, is drawn from the
// current point to (x, y).
x = nextEnhancedCoordinate(tt, str);
y = nextEnhancedCoordinate(tt, str);
path.quadrantXTo(x, y);
break;
case 'Y':
// elliptical-quadranty (x y) +
// Draws a quarter ellipse, whose initial segment is
// tangential to the y-axis, is drawn from the
// current point to(x, y).
x = nextEnhancedCoordinate(tt, str);
y = nextEnhancedCoordinate(tt, str);
path.quadrantYTo(x, y);
break;
case 'Q':
// quadratic-curveto(x1 y1 x y)+
// Draws a quadratic BeÌzier curve from the current point
// to(x, y) using(x1, y1) as the control point. (x, y)
// becomes the new current point at the end of the command.
x1 = nextEnhancedCoordinate(tt, str);
y1 = nextEnhancedCoordinate(tt, str);
x = nextEnhancedCoordinate(tt, str);
y = nextEnhancedCoordinate(tt, str);
path.quadTo(x1, y1, x, y);
break;
default:
if (DEBUG) {
System.out.println("ODGInputFormat.toEnhancedPath aborting after illegal path command: " + command + " found in path " + str);
}
break Commands;
//throw new IOException("Illegal command: "+command);
}
}
return path;
}
// in java/org/jhotdraw/samples/odg/io/ODGInputFormat.java
private Object nextEnhancedCoordinate(StreamPosTokenizer tt, String str) throws IOException {
switch (tt.nextToken()) {
case '?': {
StringBuilder buf = new StringBuilder();
buf.append('?');
int ch = tt.nextChar();
for (; ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9';
ch = tt.nextChar()) {
buf.append((char) ch);
}
tt.pushCharBack(ch);
return buf.toString();
}
case '$': {
StringBuilder buf = new StringBuilder();
buf.append('$');
int ch = tt.nextChar();
for (; ch >= '0' && ch <= '9';
ch = tt.nextChar()) {
buf.append((char) ch);
}
tt.pushCharBack(ch);
return buf.toString();
}
case StreamPosTokenizer.TT_NUMBER:
return tt.nval;
default:
throw new IOException("coordinate missing at position" + tt.getStartPosition() + " in " + str);
}
}
// in java/org/jhotdraw/samples/odg/io/ODGInputFormat.java
private void readCommonDrawingShapeAttributes(IXMLElement elem, HashMap<AttributeKey, Object> a) throws IOException {
// The attribute draw:name assigns a name to the drawing shape.
NAME.put(a, elem.getAttribute("name", DRAWING_NAMESPACE, null));
// The draw:transform attribute specifies a list of transformations that
// can be applied to a drawing shape.
TRANSFORM.put(a, toTransform(elem.getAttribute("transform", DRAWING_NAMESPACE, null)));
}
// in java/org/jhotdraw/samples/odg/io/ODGInputFormat.java
private AffineTransform readViewBoxTransform(IXMLElement elem) throws IOException {
AffineTransform tx = new AffineTransform();
Rectangle2D.Double figureBounds = new Rectangle2D.Double(
toLength(elem.getAttribute("x", SVG_NAMESPACE, "0"), 1),
toLength(elem.getAttribute("y", SVG_NAMESPACE, "0"), 1),
toLength(elem.getAttribute("width", SVG_NAMESPACE, "0"), 1),
toLength(elem.getAttribute("height", SVG_NAMESPACE, "0"), 1));
tx.translate(figureBounds.x, figureBounds.y);
// The svg:viewBox attribute establishes a user coordinate system inside the physical coordinate
// system of the shape specified by the position and size attributes. This user coordinate system is
// used by the svg:points attribute and the <draw:path> element.
// The syntax for using this attribute is the same as the [SVG] syntax. The value of the attribute are
// four numbers separated by white spaces, which define the left, top, right, and bottom dimensions
// of the user coordinate system.
// Some implementations may ignore the view box attribute. The implied coordinate system then has
// its origin at the left, top corner of the shape, without any scaling relative to the shape.
String[] viewBoxValues = toWSOrCommaSeparatedArray(elem.getAttribute("viewBox", SVG_NAMESPACE, null));
if (viewBoxValues.length == 4) {
Rectangle2D.Double viewBox = new Rectangle2D.Double(
toNumber(viewBoxValues[0]),
toNumber(viewBoxValues[1]),
toNumber(viewBoxValues[2]),
toNumber(viewBoxValues[3]));
if (!viewBox.isEmpty() && !figureBounds.isEmpty()) {
tx.scale(figureBounds.width / viewBox.width,
figureBounds.height / viewBox.height);
tx.translate(-viewBox.x, -viewBox.y);
}
}
return tx;
}
// in java/org/jhotdraw/samples/odg/io/ODGInputFormat.java
public static AffineTransform toTransform(String str) throws IOException {
AffineTransform t = new AffineTransform();
AffineTransform t2 = new AffineTransform();
if (str != null) {
StreamPosTokenizer tt = new StreamPosTokenizer(new StringReader(str));
tt.resetSyntax();
tt.wordChars('a', 'z');
tt.wordChars('A', 'Z');
tt.wordChars(128 + 32, 255);
tt.whitespaceChars(0, ' ');
tt.whitespaceChars(',', ',');
tt.parseNumbers();
tt.parseExponents();
while (tt.nextToken() != StreamPosTokenizer.TT_EOF) {
if (tt.ttype != StreamPosTokenizer.TT_WORD) {
throw new IOException("Illegal transform " + str);
}
String type = tt.sval;
if (tt.nextToken() != '(') {
throw new IOException("'(' not found in transform " + str);
}
if (type.equals("matrix")) {
double[] m = new double[6];
for (int i = 0; i < 6; i++) {
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("Matrix value " + i + " not found in transform " + str + " token:" + tt.ttype + " " + tt.sval);
}
m[i] = tt.nval;
}
t.preConcatenate(new AffineTransform(m));
} else if (type.equals("translate")) {
double tx, ty;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("X-translation value not found in transform " + str);
}
tx = tt.nval;
if (tt.nextToken() == StreamPosTokenizer.TT_WORD) {
tx *= toUnitFactor(tt.sval);
} else {
tt.pushBack();
}
if (tt.nextToken() == StreamPosTokenizer.TT_NUMBER) {
ty = tt.nval;
if (tt.nextToken() == StreamPosTokenizer.TT_WORD) {
ty *= toUnitFactor(tt.sval);
} else {
tt.pushBack();
}
} else {
tt.pushBack();
ty = 0;
}
t2.setToIdentity();
t2.translate(tx, ty);
t.preConcatenate(t2);
} else if (type.equals("scale")) {
double sx, sy;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("X-scale value not found in transform " + str);
}
sx = tt.nval;
if (tt.nextToken() == StreamPosTokenizer.TT_NUMBER) {
sy = tt.nval;
} else {
tt.pushBack();
sy = sx;
}
t2.setToIdentity();
t2.scale(sx, sy);
t.preConcatenate(t2);
} else if (type.equals("rotate")) {
double angle, cx, cy;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("Angle value not found in transform " + str);
}
angle = tt.nval;
t2.setToIdentity();
t2.rotate(-angle);
t.preConcatenate(t2);
} else if (type.equals("skewX")) {
double angle;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("Skew angle not found in transform " + str);
}
angle = tt.nval;
t.preConcatenate(new AffineTransform(
1, 0, Math.tan(angle * Math.PI / 180), 1, 0, 0));
} else if (type.equals("skewY")) {
double angle;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("Skew angle not found in transform " + str);
}
angle = tt.nval;
t.preConcatenate(new AffineTransform(
1, Math.tan(angle * Math.PI / 180), 0, 1, 0, 0));
} else {
throw new IOException("Unknown transform " + type + " in " + str);
}
if (tt.nextToken() != ')') {
throw new IOException("')' not found in transform " + str);
}
}
}
return t;
}
// in java/org/jhotdraw/samples/odg/io/ODGInputFormat.java
private BezierPath[] toPath(String str) throws IOException {
LinkedList<BezierPath> paths = new LinkedList<BezierPath>();
BezierPath path = null;
Point2D.Double p = new Point2D.Double();
Point2D.Double c1 = new Point2D.Double();
Point2D.Double c2 = new Point2D.Double();
StreamPosTokenizer tt = new StreamPosTokenizer(new StringReader(str));
tt.resetSyntax();
tt.parseNumbers();
tt.parseExponents();
tt.parsePlusAsNumber();
tt.whitespaceChars(0, ' ');
tt.whitespaceChars(',', ',');
char nextCommand = 'M';
char command = 'M';
Commands:
while (tt.nextToken() != StreamPosTokenizer.TT_EOF) {
if (tt.ttype > 0) {
command = (char) tt.ttype;
} else {
command = nextCommand;
tt.pushBack();
}
BezierPath.Node node;
switch (command) {
case 'M':
// absolute-moveto x y
if (path != null) {
paths.add(path);
}
path = new BezierPath();
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("x coordinate missing for 'M' at position " + tt.getStartPosition() + " in " + str);
}
p.x = tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("y coordinate missing for 'M' at position " + tt.getStartPosition() + " in " + str);
}
p.y = tt.nval;
path.moveTo(p.x, p.y);
nextCommand = 'L';
break;
case 'm':
// relative-moveto dx dy
if (path != null) {
paths.add(path);
}
path = new BezierPath();
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dx coordinate missing for 'm' at position " + tt.getStartPosition() + " in " + str);
}
p.x += tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dy coordinate missing for 'm' at position " + tt.getStartPosition() + " in " + str);
}
p.y += tt.nval;
path.moveTo(p.x, p.y);
nextCommand = 'l';
break;
case 'Z':
case 'z':
// close path
p.x = path.get(0).x[0];
p.y = path.get(0).y[0];
// If the last point and the first point are the same, we
// can merge them
if (path.size() > 1) {
BezierPath.Node first = path.get(0);
BezierPath.Node last = path.get(path.size() - 1);
if (first.x[0] == last.x[0]
&& first.y[0] == last.y[0]) {
if ((last.mask & BezierPath.C1_MASK) != 0) {
first.mask |= BezierPath.C1_MASK;
first.x[1] = last.x[1];
first.y[1] = last.y[1];
}
path.remove(path.size() - 1);
}
}
path.setClosed(true);
break;
case 'L':
// absolute-lineto x y
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("x coordinate missing for 'L' at position " + tt.getStartPosition() + " in " + str);
}
p.x = tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("y coordinate missing for 'L' at position " + tt.getStartPosition() + " in " + str);
}
p.y = tt.nval;
path.lineTo(p.x, p.y);
nextCommand = 'L';
break;
case 'l':
// relative-lineto dx dy
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dx coordinate missing for 'l' at position " + tt.getStartPosition() + " in " + str);
}
p.x += tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dy coordinate missing for 'l' at position " + tt.getStartPosition() + " in " + str);
}
p.y += tt.nval;
path.lineTo(p.x, p.y);
nextCommand = 'l';
break;
case 'H':
// absolute-horizontal-lineto x
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("x coordinate missing for 'H' at position " + tt.getStartPosition() + " in " + str);
}
p.x = tt.nval;
path.lineTo(p.x, p.y);
nextCommand = 'H';
break;
case 'h':
// relative-horizontal-lineto dx
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dx coordinate missing for 'h' at position " + tt.getStartPosition() + " in " + str);
}
p.x += tt.nval;
path.lineTo(p.x, p.y);
nextCommand = 'h';
break;
case 'V':
// absolute-vertical-lineto y
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("y coordinate missing for 'V' at position " + tt.getStartPosition() + " in " + str);
}
p.y = tt.nval;
path.lineTo(p.x, p.y);
nextCommand = 'V';
break;
case 'v':
// relative-vertical-lineto dy
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dy coordinate missing for 'v' at position " + tt.getStartPosition() + " in " + str);
}
p.y += tt.nval;
path.lineTo(p.x, p.y);
nextCommand = 'v';
break;
case 'C':
// absolute-curveto x1 y1 x2 y2 x y
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("x1 coordinate missing for 'C' at position " + tt.getStartPosition() + " in " + str);
}
c1.x = tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("y1 coordinate missing for 'C' at position " + tt.getStartPosition() + " in " + str);
}
c1.y = tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("x2 coordinate missing for 'C' at position " + tt.getStartPosition() + " in " + str);
}
c2.x = tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("y2 coordinate missing for 'C' at position " + tt.getStartPosition() + " in " + str);
}
c2.y = tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("x coordinate missing for 'C' at position " + tt.getStartPosition() + " in " + str);
}
p.x = tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("y coordinate missing for 'C' at position " + tt.getStartPosition() + " in " + str);
}
p.y = tt.nval;
path.curveTo(c1.x, c1.y, c2.x, c2.y, p.x, p.y);
nextCommand = 'C';
break;
case 'c':
// relative-curveto dx1 dy1 dx2 dy2 dx dy
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dx1 coordinate missing for 'c' at position " + tt.getStartPosition() + " in " + str);
}
c1.x = p.x + tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dy1 coordinate missing for 'c' at position " + tt.getStartPosition() + " in " + str);
}
c1.y = p.y + tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dx2 coordinate missing for 'c' at position " + tt.getStartPosition() + " in " + str);
}
c2.x = p.x + tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dy2 coordinate missing for 'c' at position " + tt.getStartPosition() + " in " + str);
}
c2.y = p.y + tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dx coordinate missing for 'c' at position " + tt.getStartPosition() + " in " + str);
}
p.x += tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dy coordinate missing for 'c' at position " + tt.getStartPosition() + " in " + str);
}
p.y += tt.nval;
path.curveTo(c1.x, c1.y, c2.x, c2.y, p.x, p.y);
nextCommand = 'c';
break;
case 'S':
// absolute-shorthand-curveto x2 y2 x y
node = path.get(path.size() - 1);
c1.x = node.x[0] * 2d - node.x[1];
c1.y = node.y[0] * 2d - node.y[1];
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("x2 coordinate missing for 'S' at position " + tt.getStartPosition() + " in " + str);
}
c2.x = tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("y2 coordinate missing for 'S' at position " + tt.getStartPosition() + " in " + str);
}
c2.y = tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("x coordinate missing for 'S' at position " + tt.getStartPosition() + " in " + str);
}
p.x = tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("y coordinate missing for 'S' at position " + tt.getStartPosition() + " in " + str);
}
p.y = tt.nval;
path.curveTo(c1.x, c1.y, c2.x, c2.y, p.x, p.y);
nextCommand = 'S';
break;
case 's':
// relative-shorthand-curveto dx2 dy2 dx dy
node = path.get(path.size() - 1);
c1.x = node.x[0] * 2d - node.x[1];
c1.y = node.y[0] * 2d - node.y[1];
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dx2 coordinate missing for 's' at position " + tt.getStartPosition() + " in " + str);
}
c2.x = p.x + tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dy2 coordinate missing for 's' at position " + tt.getStartPosition() + " in " + str);
}
c2.y = p.y + tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dx coordinate missing for 's' at position " + tt.getStartPosition() + " in " + str);
}
p.x += tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dy coordinate missing for 's' at position " + tt.getStartPosition() + " in " + str);
}
p.y += tt.nval;
path.curveTo(c1.x, c1.y, c2.x, c2.y, p.x, p.y);
nextCommand = 's';
break;
case 'Q':
// absolute-quadto x1 y1 x y
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("x1 coordinate missing for 'Q' at position " + tt.getStartPosition() + " in " + str);
}
c1.x = tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("y1 coordinate missing for 'Q' at position " + tt.getStartPosition() + " in " + str);
}
c1.y = tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("x coordinate missing for 'Q' at position " + tt.getStartPosition() + " in " + str);
}
p.x = tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("y coordinate missing for 'Q' at position " + tt.getStartPosition() + " in " + str);
}
p.y = tt.nval;
path.quadTo(c1.x, c1.y, p.x, p.y);
nextCommand = 'Q';
break;
case 'q':
// relative-quadto dx1 dy1 dx dy
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dx1 coordinate missing for 'q' at position " + tt.getStartPosition() + " in " + str);
}
c1.x = p.x + tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dy1 coordinate missing for 'q' at position " + tt.getStartPosition() + " in " + str);
}
c1.y = p.y + tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dx coordinate missing for 'q' at position " + tt.getStartPosition() + " in " + str);
}
p.x += tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dy coordinate missing for 'q' at position " + tt.getStartPosition() + " in " + str);
}
p.y += tt.nval;
path.quadTo(c1.x, c1.y, p.x, p.y);
nextCommand = 'q';
break;
case 'T':
// absolute-shorthand-quadto x y
node = path.get(path.size() - 1);
c1.x = node.x[0] * 2d - node.x[1];
c1.y = node.y[0] * 2d - node.y[1];
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("x coordinate missing for 'T' at position " + tt.getStartPosition() + " in " + str);
}
p.x = tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("y coordinate missing for 'T' at position " + tt.getStartPosition() + " in " + str);
}
p.y = tt.nval;
path.quadTo(c1.x, c1.y, p.x, p.y);
nextCommand = 'T';
break;
case 't':
// relative-shorthand-quadto dx dy
node = path.get(path.size() - 1);
c1.x = node.x[0] * 2d - node.x[1];
c1.y = node.y[0] * 2d - node.y[1];
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dx coordinate missing for 't' at position " + tt.getStartPosition() + " in " + str);
}
p.x += tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("dy coordinate missing for 't' at position " + tt.getStartPosition() + " in " + str);
}
p.y += tt.nval;
path.quadTo(c1.x, c1.y, p.x, p.y);
nextCommand = 's';
break;
case 'A': {
// absolute-elliptical-arc rx ry x-axis-rotation large-arc-flag sweep-flag x y
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("rx coordinate missing for 'A' at position " + tt.getStartPosition() + " in " + str);
}
// If rX or rY have negative signs, these are dropped;
// the absolute value is used instead.
double rx = tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("ry coordinate missing for 'A' at position " + tt.getStartPosition() + " in " + str);
}
double ry = tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("x-axis-rotation missing for 'A' at position " + tt.getStartPosition() + " in " + str);
}
double xAxisRotation = tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("large-arc-flag missing for 'A' at position " + tt.getStartPosition() + " in " + str);
}
boolean largeArcFlag = tt.nval != 0;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("sweep-flag missing for 'A' at position " + tt.getStartPosition() + " in " + str);
}
boolean sweepFlag = tt.nval != 0;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("x coordinate missing for 'A' at position " + tt.getStartPosition() + " in " + str);
}
p.x = tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("y coordinate missing for 'A' at position " + tt.getStartPosition() + " in " + str);
}
p.y = tt.nval;
path.arcTo(rx, ry, xAxisRotation, largeArcFlag, sweepFlag, p.x, p.y);
nextCommand = 'A';
break;
}
case 'a': {
// absolute-elliptical-arc rx ry x-axis-rotation large-arc-flag sweep-flag x y
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("rx coordinate missing for 'A' at position " + tt.getStartPosition() + " in " + str);
}
// If rX or rY have negative signs, these are dropped;
// the absolute value is used instead.
double rx = tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("ry coordinate missing for 'A' at position " + tt.getStartPosition() + " in " + str);
}
double ry = tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("x-axis-rotation missing for 'A' at position " + tt.getStartPosition() + " in " + str);
}
double xAxisRotation = tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("large-arc-flag missing for 'A' at position " + tt.getStartPosition() + " in " + str);
}
boolean largeArcFlag = tt.nval != 0;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("sweep-flag missing for 'A' at position " + tt.getStartPosition() + " in " + str);
}
boolean sweepFlag = tt.nval != 0;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("x coordinate missing for 'A' at position " + tt.getStartPosition() + " in " + str);
}
p.x += tt.nval;
if (tt.nextToken() != StreamPosTokenizer.TT_NUMBER) {
throw new IOException("y coordinate missing for 'A' at position " + tt.getStartPosition() + " in " + str);
}
p.y += tt.nval;
path.arcTo(rx, ry, xAxisRotation, largeArcFlag, sweepFlag, p.x, p.y);
nextCommand = 'a';
break;
}
default:
if (DEBUG) {
System.out.println("SVGInputFormat.toPath aborting after illegal path command: " + command + " found in path " + str);
}
break Commands;
//throw new IOException("Illegal command: "+command);
}
}
if (path != null) {
paths.add(path);
}
return paths.toArray(new BezierPath[paths.size()]);
}
// in java/org/jhotdraw/samples/odg/io/ODGStylesReader.java
public void read(File file) throws IOException {
BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
try {
read(in);
} finally {
in.close();
}
}
// in java/org/jhotdraw/samples/odg/io/ODGStylesReader.java
public void read(InputStream in) throws IOException {
IXMLParser parser;
try {
parser = XMLParserFactory.createDefaultXMLParser();
} catch (Exception ex) {
InternalError e = new InternalError("Unable to instantiate NanoXML Parser");
e.initCause(ex);
throw e;
}
IXMLReader reader = new StdXMLReader(in);
parser.setReader(reader);
IXMLElement document;
try {
document = (IXMLElement) parser.parse();
} catch (XMLException ex) {
IOException e = new IOException(ex.getMessage());
e.initCause(ex);
throw e;
}
read(document);
}
// in java/org/jhotdraw/samples/odg/io/ODGStylesReader.java
public void read(IXMLElement root) throws IOException {
String name = root.getName();
String ns = root.getNamespace();
if (name.equals("document-content") && (ns == null || ns.equals(OFFICE_NAMESPACE))) {
readDocumentContentElement(root);
} else if (name.equals("document-styles") && (ns == null || ns.equals(OFFICE_NAMESPACE))) {
readDocumentStylesElement(root);
} else {
if (DEBUG) {
System.out.println("ODGStylesReader unsupported root element " + root);
}
}
}
// in java/org/jhotdraw/samples/odg/io/ODGStylesReader.java
private void readDefaultStyleElement(IXMLElement elem, HashMap<String, Style> styles) throws IOException {
String styleName = elem.getAttribute("family", STYLE_NAMESPACE, null);
String family = elem.getAttribute("family", STYLE_NAMESPACE, null);
String parentStyleName = elem.getAttribute("parent-style-name", STYLE_NAMESPACE, null);
if (DEBUG) {
System.out.println("ODGStylesReader <default-style family=" + styleName + " ...>...</>");
}
if (styleName != null) {
Style a = styles.get(styleName);
if (a == null) {
a = new Style();
a.name = styleName;
a.family = family;
a.parentName = parentStyleName;
styles.put(styleName, a);
}
for (IXMLElement child : elem.getChildren()) {
String ns = child.getNamespace();
String name = child.getName();
if (name.equals("drawing-page-properties") && (ns == null || ns.equals(STYLE_NAMESPACE))) {
readDrawingPagePropertiesElement(child, a);
} else if (name.equals("graphic-properties") && (ns == null || ns.equals(STYLE_NAMESPACE))) {
readGraphicPropertiesElement(child, a);
} else if (name.equals("paragraph-properties") && (ns == null || ns.equals(STYLE_NAMESPACE))) {
readParagraphPropertiesElement(child, a);
} else if (name.equals("text-properties") && (ns == null || ns.equals(STYLE_NAMESPACE))) {
readTextPropertiesElement(child, a);
} else {
if (DEBUG) {
System.out.println("ODGStylesReader unsupported <" + elem.getName() + "> child " + child);
}
}
}
}
}
// in java/org/jhotdraw/samples/odg/io/ODGStylesReader.java
private void readDocumentContentElement(IXMLElement elem) throws IOException {
if (DEBUG) {
System.out.println("ODGStylesReader <" + elem.getName() + " ...>");
}
for (IXMLElement child : elem.getChildren()) {
String ns = child.getNamespace();
String name = child.getName();
if (name.equals("automatic-styles") && (ns == null || ns.equals(OFFICE_NAMESPACE))) {
readAutomaticStylesElement(child);
} else if (name.equals("master-styles") && (ns == null || ns.equals(OFFICE_NAMESPACE))) {
readStylesElement(child);
} else if (name.equals("styles") && (ns == null || ns.equals(OFFICE_NAMESPACE))) {
readStylesElement(child);
}
}
if (DEBUG) {
System.out.println("ODGStylesReader </" + elem.getName() + ">");
}
}
// in java/org/jhotdraw/samples/odg/io/ODGStylesReader.java
private void readDocumentStylesElement(IXMLElement elem) throws IOException {
if (DEBUG) {
System.out.println("ODGStylesReader <" + elem.getName() + " ...>");
}
for (IXMLElement child : elem.getChildren()) {
String ns = child.getNamespace();
String name = child.getName();
if (name.equals("styles") && (ns == null || ns.equals(OFFICE_NAMESPACE))) {
readStylesElement(child);
} else if (name.equals("automatic-styles") && (ns == null || ns.equals(OFFICE_NAMESPACE))) {
readAutomaticStylesElement(child);
} else if (name.equals("master-styles") && (ns == null || ns.equals(OFFICE_NAMESPACE))) {
readMasterStylesElement(child);
} else {
if (DEBUG) {
System.out.println("ODGStylesReader unsupported <" + elem.getName() + "> child " + child);
}
}
}
if (DEBUG) {
System.out.println("ODGStylesReader </" + elem.getName() + ">");
}
}
// in java/org/jhotdraw/samples/odg/io/ODGStylesReader.java
private void readDrawingPagePropertiesElement(IXMLElement elem, HashMap<AttributeKey, Object> a) throws IOException {
if (DEBUG) {
System.out.println("ODGStylesReader unsupported <" + elem.getName() + "> element.");
}
}
// in java/org/jhotdraw/samples/odg/io/ODGStylesReader.java
private void readGraphicPropertiesElement(IXMLElement elem, HashMap<AttributeKey, Object> a) throws IOException {
// The attribute draw:stroke specifies the style of the stroke on the current object. The value
// none means that no stroke is drawn, and the value solid means that a solid stroke is drawn. If
// the value is dash, the stroke referenced by the draw:stroke-dash property is drawn.
if (elem.hasAttribute("stroke", DRAWING_NAMESPACE)) {
STROKE_STYLE.put(a, (StrokeStyle) elem.getAttribute("stroke", DRAWING_NAMESPACE, STROKE_STYLES, null));
}
// The attribute svg:stroke-width specifies the width of the stroke on
// the current object.
if (elem.hasAttribute("stroke-width", SVG_NAMESPACE)) {
STROKE_WIDTH.put(a, toLength(elem.getAttribute("stroke-width", SVG_NAMESPACE, null)));
}
// The attribute svg:stroke-color specifies the color of the stroke on
// the current object.
if (elem.hasAttribute("stroke-color", SVG_NAMESPACE)) {
STROKE_COLOR.put(a, toColor(elem.getAttribute("stroke-color", SVG_NAMESPACE, null)));
}
// FIXME read draw:marker-start-width, draw:marker-start-center, draw:marker-end-width,
// draw:marker-end-centre
// The attribute draw:fill specifies the fill style for a graphic
// object. Graphic objects that are not closed, such as a path without a
// closepath at the end, will not be filled. The fill operation does not
// automatically close all open subpaths by connecting the last point of
// the subpath with the first point of the subpath before painting the
// fill. The attribute has the following values:
// • none: the drawing object is not filled.
// • solid: the drawing object is filled with color specified by the
// draw:fill-color attribute.
// • bitmap: the drawing object is filled with the bitmap specified
// by the draw:fill-image-name attribute.
// • gradient: the drawing object is filled with the gradient specified
// by the draw:fill-gradient-name attribute.
// • hatch: the drawing object is filled with the hatch specified by
// the draw:fill-hatch-name attribute.
if (elem.hasAttribute("fill", DRAWING_NAMESPACE)) {
FILL_STYLE.put(a, (FillStyle) elem.getAttribute("fill", DRAWING_NAMESPACE, FILL_STYLES, null));
}
// The attribute draw:fill-color specifies the color of the fill for a
// graphic object. It is used only if the draw:fill attribute has the
// value solid.
if (elem.hasAttribute("fill-color", DRAWING_NAMESPACE)) {
FILL_COLOR.put(a, toColor(elem.getAttribute("fill-color", DRAWING_NAMESPACE, null)));
}
// FIXME read fo:padding-top, fo:padding-bottom, fo:padding-left,
// fo:padding-right
// FIXME read draw:shadow, draw:shadow-offset-x, draw:shadow-offset-y,
// draw:shadow-color
for (IXMLElement child : elem.getChildren()) {
String ns = child.getNamespace();
String name = child.getName();
// if (DEBUG) System.out.println("ODGStylesReader unsupported <"+elem.getName()+"> child <"+child.getName()+" ...>...</>");
}
}
// in java/org/jhotdraw/samples/odg/io/ODGStylesReader.java
private void readStyleElement(IXMLElement elem, HashMap<String, Style> styles) throws IOException {
// The style:name attribute identifies the name of the style. This attribute, combined with the
// style:family attribute, uniquely identifies a style. The <office:styles>,
// <office:automatic-styles> and <office:master-styles> elements each must not
// contain two styles with the same family and the same name.
// For automatic styles, a name is generated during document export. If the document is exported
// several times, it cannot be assumed that the same name is generated each time.
// In an XML document, the name of each style is a unique name that may be independent of the
// language selected for an office applications user interface. Usually these names are the ones used
// for the English version of the user interface.
String styleName = elem.getAttribute("name", STYLE_NAMESPACE, null);
String family = elem.getAttribute("family", STYLE_NAMESPACE, null);
String parentStyleName = elem.getAttribute("parent-style-name", STYLE_NAMESPACE, null);
if (DEBUG) {
System.out.println("ODGStylesReader <style name=" + styleName + " ...>...</>");
}
if (styleName != null) {
Style a = styles.get(styleName);
if (a == null) {
a = new Style();
a.name = styleName;
a.family = family;
a.parentName = parentStyleName;
styles.put(styleName, a);
}
for (IXMLElement child : elem.getChildren()) {
String ns = child.getNamespace();
String name = child.getName();
if (name.equals("drawing-page-properties") && (ns == null || ns.equals(STYLE_NAMESPACE))) {
readDrawingPagePropertiesElement(child, a);
} else if (name.equals("graphic-properties") && (ns == null || ns.equals(STYLE_NAMESPACE))) {
readGraphicPropertiesElement(child, a);
} else if (name.equals("paragraph-properties") && (ns == null || ns.equals(STYLE_NAMESPACE))) {
readParagraphPropertiesElement(child, a);
} else if (name.equals("text-properties") && (ns == null || ns.equals(STYLE_NAMESPACE))) {
readTextPropertiesElement(child, a);
} else {
if (DEBUG) {
System.out.println("ODGStylesReader unsupported <" + elem.getName() + "> child " + child);
}
}
}
}
}
// in java/org/jhotdraw/samples/odg/io/ODGStylesReader.java
private void readStylesElement(IXMLElement elem) throws IOException {
readStylesChildren(elem, commonStyles);
}
// in java/org/jhotdraw/samples/odg/io/ODGStylesReader.java
private void readStylesChildren(IXMLElement elem,
HashMap<String, Style> styles) throws IOException {
for (IXMLElement child : elem.getChildren()) {
String ns = child.getNamespace();
String name = child.getName();
if (name.equals("default-style") && (ns == null || ns.equals(STYLE_NAMESPACE))) {
readDefaultStyleElement(child, styles);
} else if (name.equals("layer-set") && (ns == null || ns.equals(DRAWING_NAMESPACE))) {
readLayerSetElement(child, styles);
} else if (name.equals("list-style") && (ns == null || ns.equals(TEXT_NAMESPACE))) {
readListStyleElement(child, styles);
} else if (name.equals("marker") && (ns == null || ns.equals(DRAWING_NAMESPACE))) {
readMarkerElement(child, styles);
} else if (name.equals("master-page") && (ns == null || ns.equals(STYLE_NAMESPACE))) {
readMasterPageElement(child, styles);
} else if (name.equals("page-layout") && (ns == null || ns.equals(STYLE_NAMESPACE))) {
readPageLayoutElement(child, styles);
//} else if (name.equals("paragraph-properties") && (ns == null || ns.equals(STYLE_NAMESPACE))) {
// readParagraphPropertiesElement(child, styles);
} else if (name.equals("style") && (ns == null || ns.equals(STYLE_NAMESPACE))) {
readStyleElement(child, styles);
//} else if (name.equals("text-properties") && (ns == null || ns.equals(STYLE_NAMESPACE))) {
// readTextPropertiesElement(child, styles);
} else {
if (DEBUG) {
System.out.println("ODGStylesReader unsupported <" + elem.getName() + "> child: " + child);
}
}
}
}
// in java/org/jhotdraw/samples/odg/io/ODGStylesReader.java
private void readAutomaticStylesElement(IXMLElement elem) throws IOException {
readStylesChildren(elem, automaticStyles);
}
// in java/org/jhotdraw/samples/odg/io/ODGStylesReader.java
private void readLayerSetElement(IXMLElement elem, HashMap<String, Style> styles) throws IOException {
if (DEBUG) {
System.out.println("ODGStylesReader unsupported <" + elem.getName() + "> element.");
}
}
// in java/org/jhotdraw/samples/odg/io/ODGStylesReader.java
private void readListStyleElement(IXMLElement elem, HashMap<String, Style> styles) throws IOException {
if (DEBUG) {
System.out.println("ODGStylesReader unsupported <" + elem.getName() + "> element.");
}
}
// in java/org/jhotdraw/samples/odg/io/ODGStylesReader.java
private void readMasterStylesElement(IXMLElement elem) throws IOException {
readStylesChildren(elem, masterStyles);
}
// in java/org/jhotdraw/samples/odg/io/ODGStylesReader.java
private void readMarkerElement(IXMLElement elem, HashMap<String, Style> styles) throws IOException {
//if (DEBUG) System.out.println("ODGStylesReader unsupported <"+elem.getName()+"> element.");
}
// in java/org/jhotdraw/samples/odg/io/ODGStylesReader.java
private void readMasterPageElement(IXMLElement elem, HashMap<String, Style> styles) throws IOException {
if (DEBUG) {
System.out.println("ODGStylesReader unsupported <" + elem.getName() + "> element.");
}
}
// in java/org/jhotdraw/samples/odg/io/ODGStylesReader.java
private void readPageLayoutElement(IXMLElement elem, HashMap<String, Style> styles) throws IOException {
//if (DEBUG) System.out.println("ODGStylesReader unsupported <"+elem.getName()+"> element.");
}
// in java/org/jhotdraw/samples/odg/io/ODGStylesReader.java
private void readParagraphPropertiesElement(IXMLElement elem, HashMap<AttributeKey, Object> a) throws IOException {
//if (DEBUG) System.out.println("ODGStylesReader unsupported <"+elem.getName()+"> element.");
}
// in java/org/jhotdraw/samples/odg/io/ODGStylesReader.java
private void readTextPropertiesElement(IXMLElement elem, HashMap<AttributeKey, Object> a) throws IOException {
//if (DEBUG) System.out.println("ODGStylesReader unsupported <"+elem.getName()+"> element.");
}
// in java/org/jhotdraw/samples/odg/io/ODGStylesReader.java
private double toLength(String str) throws IOException {
double scaleFactor = 1d;
if (str == null || str.length() == 0) {
return 0d;
}
if (str.endsWith("cm")) {
str = str.substring(0, str.length() - 2);
scaleFactor = 35.43307;
} else if (str.endsWith("mm")) {
str = str.substring(0, str.length() - 2);
scaleFactor = 3.543307;
} else if (str.endsWith("in")) {
str = str.substring(0, str.length() - 2);
scaleFactor = 90;
} else if (str.endsWith("pt")) {
str = str.substring(0, str.length() - 2);
scaleFactor = 1.25;
} else if (str.endsWith("pc")) {
str = str.substring(0, str.length() - 2);
scaleFactor = 15;
} else if (str.endsWith("px")) {
str = str.substring(0, str.length() - 2);
}
return Double.parseDouble(str) * scaleFactor;
}
// in java/org/jhotdraw/samples/odg/io/ODGStylesReader.java
Nullable
private Color toColor(String value) throws IOException {
String str = value;
if (str == null) {
return null;
}
if (str.startsWith("#") && str.length() == 7) {
return new Color(Integer.decode(str));
} else {
return null;
}
}
// in java/org/jhotdraw/samples/odg/ODGView.java
Override
public void write(URI f, URIChooser fc) throws IOException {
new SVGOutputFormat().write(new File(f), view.getDrawing());
}
// in java/org/jhotdraw/samples/teddy/TeddyView.java
Override
public void read(URI f, URIChooser chooser) throws IOException {
String characterSet;
if (chooser == null//
|| !(chooser instanceof JFileURIChooser) //
|| !(((JFileURIChooser) chooser).getAccessory() instanceof CharacterSetAccessory)//
) {
characterSet = prefs.get("characterSet", "UTF-8");
} else {
characterSet = ((CharacterSetAccessory) ((JFileURIChooser) chooser).getAccessory()).getCharacterSet();
}
read(f, characterSet);
}
// in java/org/jhotdraw/samples/teddy/TeddyView.java
public void read(URI f, String characterSet) throws IOException {
final Document doc = readDocument(new File(f), characterSet);
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
editor.getDocument().removeUndoableEditListener(undoManager);
editor.setDocument(doc);
doc.addUndoableEditListener(undoManager);
undoManager.discardAllEdits();
}
});
} catch (InterruptedException e) {
// ignore
} catch (InvocationTargetException e) {
InternalError error = new InternalError(e.getMessage());
error.initCause(e);
throw error;
}
}
// in java/org/jhotdraw/samples/teddy/TeddyView.java
Override
public void write(URI f, URIChooser chooser) throws IOException {
String characterSet, lineSeparator;
if (chooser == null//
|| !(chooser instanceof JFileURIChooser) //
|| !(((JFileURIChooser) chooser).getAccessory() instanceof CharacterSetAccessory)//
) {
characterSet = prefs.get("characterSet", "UTF-8");
lineSeparator = prefs.get("lineSeparator", "\n");
} else {
characterSet = ((CharacterSetAccessory) ((JFileURIChooser) chooser).getAccessory()).getCharacterSet();
lineSeparator = ((CharacterSetAccessory) ((JFileURIChooser) chooser).getAccessory()).getLineSeparator();
}
write(f, characterSet, lineSeparator);
}
// in java/org/jhotdraw/samples/teddy/TeddyView.java
public void write(URI f, String characterSet, String lineSeparator) throws IOException {
writeDocument(editor.getDocument(), new File(f), characterSet, lineSeparator);
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
undoManager.setHasSignificantEdits(false);
}
});
} catch (InterruptedException e) {
// ignore
} catch (InvocationTargetException e) {
InternalError error = new InternalError(e.getMessage());
error.initCause(e);
throw error;
}
}
// in java/org/jhotdraw/samples/teddy/TeddyView.java
private Document readDocument(File f, String characterSet)
throws IOException {
ProgressMonitorInputStream pin = new ProgressMonitorInputStream(this, "Reading " + f.getName(), new FileInputStream(f));
BufferedReader in = new BufferedReader(new InputStreamReader(pin, characterSet));
try {
// PlainDocument doc = new PlainDocument();
StyledDocument doc = createDocument();
MutableAttributeSet attrs = ((StyledEditorKit) editor.getEditorKit()).getInputAttributes();
String line;
boolean isFirst = true;
while ((line = in.readLine()) != null) {
if (isFirst) {
isFirst = false;
} else {
doc.insertString(doc.getLength(), "\n", attrs);
}
doc.insertString(doc.getLength(), line, attrs);
}
return doc;
} catch (BadLocationException e) {
throw new IOException(e.getMessage());
} catch (OutOfMemoryError e) {
System.err.println("out of memory!");
throw new IOException("Out of memory.");
} finally {
in.close();
}
}
// in java/org/jhotdraw/samples/teddy/TeddyView.java
private void writeDocument(Document doc, File f, String characterSet, String lineSeparator)
throws IOException {
LFWriter out = new LFWriter(new OutputStreamWriter(new FileOutputStream(f), characterSet));
out.setLineSeparator(lineSeparator);
try {
String sequence;
for (int i = 0; i < doc.getLength(); i += 256) {
out.write(doc.getText(i, Math.min(256, doc.getLength() - i)));
}
} catch (BadLocationException e) {
throw new IOException(e.getMessage());
} finally {
out.close();
undoManager.discardAllEdits();
}
}
// in java/org/jhotdraw/samples/teddy/io/LFWriter.java
Override
public void write(int c) throws IOException {
switch (c) {
case '\r':
out.write(lineSeparator);
skipLF = true;
break;
case '\n':
if (!skipLF) out.write(lineSeparator);
skipLF = false;
break;
default :
out.write(c);
skipLF = false;
break;
}
}
// in java/org/jhotdraw/samples/teddy/io/LFWriter.java
Override
public void write(char cbuf[], int off, int len) throws IOException {
int end = off + len;
for (int i=off; i < end; i++) {
switch (cbuf[i]) {
case '\r':
out.write(cbuf, off, i - off);
off = i + 1;
out.write(lineSeparator);
skipLF = true;
break;
case '\n':
out.write(cbuf, off, i - off);
off = i + 1;
if (skipLF) {
skipLF = false;
} else {
out.write(lineSeparator);
}
break;
default :
skipLF = false;
break;
}
}
if (off < end) out.write(cbuf, off, end - off);
}
// in java/org/jhotdraw/samples/teddy/io/LFWriter.java
public void write(String str, int off, int len) throws IOException {
write(str.toCharArray(), off, len);
}
// in java/org/jhotdraw/util/ResourceBundleUtil.java
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
// our "pseudo-constructor"
in.defaultReadObject();
// re-establish the "resource" variable
this.resource = ResourceBundle.getBundle(baseName, locale);
}
// in java/org/jhotdraw/util/prefs/PreferencesUtil.java
Override
public void exportNode(OutputStream os) throws IOException, BackingStoreException {
//
}
// in java/org/jhotdraw/util/prefs/PreferencesUtil.java
Override
public void exportSubtree(OutputStream os) throws IOException, BackingStoreException {
//
}