From 6025b6016517c6d898d8957d1d7e03ba71431912 Mon Sep 17 00:00:00 2001 From: tknall Date: Fri, 1 Dec 2006 12:20:24 +0000 Subject: Initial import of release 2.2. git-svn-id: https://joinup.ec.europa.eu/svn/pdf-as/trunk@4 7b5415b0-85f9-ee4d-85bd-d5d0c3b42d1c --- .../text/pdf/codec/postscript/JavaCharStream.java | 547 ++++ .../text/pdf/codec/postscript/MetaDoPS.java | 98 + .../text/pdf/codec/postscript/PACommand.java | 19 + .../text/pdf/codec/postscript/PAContext.java | 2772 ++++++++++++++++++++ .../text/pdf/codec/postscript/PAEngine.java | 155 ++ .../text/pdf/codec/postscript/PAParser.java | 351 +++ .../pdf/codec/postscript/PAParserConstants.java | 60 + .../pdf/codec/postscript/PAParserTokenManager.java | 1011 +++++++ .../text/pdf/codec/postscript/PAPencil.java | 431 +++ .../lowagie/text/pdf/codec/postscript/PAToken.java | 66 + .../pdf/codec/postscript/PainterException.java | 20 + .../text/pdf/codec/postscript/ParseException.java | 192 ++ .../lowagie/text/pdf/codec/postscript/Token.java | 81 + .../text/pdf/codec/postscript/TokenMgrError.java | 133 + 14 files changed, 5936 insertions(+) create mode 100644 src/main/java/com/lowagie/text/pdf/codec/postscript/JavaCharStream.java create mode 100644 src/main/java/com/lowagie/text/pdf/codec/postscript/MetaDoPS.java create mode 100644 src/main/java/com/lowagie/text/pdf/codec/postscript/PACommand.java create mode 100644 src/main/java/com/lowagie/text/pdf/codec/postscript/PAContext.java create mode 100644 src/main/java/com/lowagie/text/pdf/codec/postscript/PAEngine.java create mode 100644 src/main/java/com/lowagie/text/pdf/codec/postscript/PAParser.java create mode 100644 src/main/java/com/lowagie/text/pdf/codec/postscript/PAParserConstants.java create mode 100644 src/main/java/com/lowagie/text/pdf/codec/postscript/PAParserTokenManager.java create mode 100644 src/main/java/com/lowagie/text/pdf/codec/postscript/PAPencil.java create mode 100644 src/main/java/com/lowagie/text/pdf/codec/postscript/PAToken.java create mode 100644 src/main/java/com/lowagie/text/pdf/codec/postscript/PainterException.java create mode 100644 src/main/java/com/lowagie/text/pdf/codec/postscript/ParseException.java create mode 100644 src/main/java/com/lowagie/text/pdf/codec/postscript/Token.java create mode 100644 src/main/java/com/lowagie/text/pdf/codec/postscript/TokenMgrError.java (limited to 'src/main/java/com/lowagie/text/pdf/codec/postscript') diff --git a/src/main/java/com/lowagie/text/pdf/codec/postscript/JavaCharStream.java b/src/main/java/com/lowagie/text/pdf/codec/postscript/JavaCharStream.java new file mode 100644 index 0000000..da52458 --- /dev/null +++ b/src/main/java/com/lowagie/text/pdf/codec/postscript/JavaCharStream.java @@ -0,0 +1,547 @@ +/* Generated By:JavaCC: Do not edit this line. JavaCharStream.java Version 2.1 */ +package com.lowagie.text.pdf.codec.postscript; + +/** + * An implementation of interface CharStream, where the stream is assumed to + * contain only ASCII characters (with java-like unicode escape processing). + */ + +public final class JavaCharStream +{ + public static final boolean staticFlag = false; + static final int hexval(char c) throws java.io.IOException { + switch(c) + { + case '0' : + return 0; + case '1' : + return 1; + case '2' : + return 2; + case '3' : + return 3; + case '4' : + return 4; + case '5' : + return 5; + case '6' : + return 6; + case '7' : + return 7; + case '8' : + return 8; + case '9' : + return 9; + + case 'a' : + case 'A' : + return 10; + case 'b' : + case 'B' : + return 11; + case 'c' : + case 'C' : + return 12; + case 'd' : + case 'D' : + return 13; + case 'e' : + case 'E' : + return 14; + case 'f' : + case 'F' : + return 15; + } + + throw new java.io.IOException(); // Should never come here + } + + public int bufpos = -1; + int bufsize; + int available; + int tokenBegin; + private int bufline[]; + private int bufcolumn[]; + + private int column = 0; + private int line = 1; + + private boolean prevCharIsCR = false; + private boolean prevCharIsLF = false; + + private java.io.Reader inputStream; + + private char[] nextCharBuf; + private char[] buffer; + private int maxNextCharInd = 0; + private int nextCharInd = -1; + private int inBuf = 0; + + private final void ExpandBuff(boolean wrapAround) + { + char[] newbuffer = new char[bufsize + 2048]; + int newbufline[] = new int[bufsize + 2048]; + int newbufcolumn[] = new int[bufsize + 2048]; + + try + { + if (wrapAround) + { + System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); + System.arraycopy(buffer, 0, newbuffer, + bufsize - tokenBegin, bufpos); + buffer = newbuffer; + + System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); + System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos); + bufline = newbufline; + + System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); + System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos); + bufcolumn = newbufcolumn; + + bufpos += (bufsize - tokenBegin); + } + else + { + System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); + buffer = newbuffer; + + System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); + bufline = newbufline; + + System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); + bufcolumn = newbufcolumn; + + bufpos -= tokenBegin; + } + } + catch (Throwable t) + { + throw new Error(t.getMessage()); + } + + available = (bufsize += 2048); + tokenBegin = 0; + } + + private final void FillBuff() throws java.io.IOException + { + int i; + if (maxNextCharInd == 4096) + maxNextCharInd = nextCharInd = 0; + + try { + if ((i = inputStream.read(nextCharBuf, maxNextCharInd, + 4096 - maxNextCharInd)) == -1) + { + inputStream.close(); + throw new java.io.IOException(); + } + else + maxNextCharInd += i; + return; + } + catch(java.io.IOException e) { + if (bufpos != 0) + { + --bufpos; + backup(0); + } + else + { + bufline[bufpos] = line; + bufcolumn[bufpos] = column; + } + throw e; + } + } + + private final char ReadByte() throws java.io.IOException + { + if (++nextCharInd >= maxNextCharInd) + FillBuff(); + + return nextCharBuf[nextCharInd]; + } + + public final char BeginToken() throws java.io.IOException + { + if (inBuf > 0) + { + --inBuf; + + if (++bufpos == bufsize) + bufpos = 0; + + tokenBegin = bufpos; + return buffer[bufpos]; + } + + tokenBegin = 0; + bufpos = -1; + + return readChar(); + } + + private final void AdjustBuffSize() + { + if (available == bufsize) + { + if (tokenBegin > 2048) + { + bufpos = 0; + available = tokenBegin; + } + else + ExpandBuff(false); + } + else if (available > tokenBegin) + available = bufsize; + else if ((tokenBegin - available) < 2048) + ExpandBuff(true); + else + available = tokenBegin; + } + + private final void UpdateLineColumn(char c) + { + column++; + + if (prevCharIsLF) + { + prevCharIsLF = false; + line += (column = 1); + } + else if (prevCharIsCR) + { + prevCharIsCR = false; + if (c == '\n') + { + prevCharIsLF = true; + } + else + line += (column = 1); + } + + switch (c) + { + case '\r' : + prevCharIsCR = true; + break; + case '\n' : + prevCharIsLF = true; + break; + case '\t' : + column--; + column += (8 - (column & 07)); + break; + default : + break; + } + + bufline[bufpos] = line; + bufcolumn[bufpos] = column; + } + + public final char readChar() throws java.io.IOException + { + if (inBuf > 0) + { + --inBuf; + + if (++bufpos == bufsize) + bufpos = 0; + + return buffer[bufpos]; + } + + char c; + + if (++bufpos == available) + AdjustBuffSize(); + + if ((buffer[bufpos] = c = ReadByte()) == '\\') + { + UpdateLineColumn(c); + + int backSlashCnt = 1; + + for (;;) // Read all the backslashes + { + if (++bufpos == available) + AdjustBuffSize(); + + try + { + if ((buffer[bufpos] = c = ReadByte()) != '\\') + { + UpdateLineColumn(c); + // found a non-backslash char. + if ((c == 'u') && ((backSlashCnt & 1) == 1)) + { + if (--bufpos < 0) + bufpos = bufsize - 1; + + break; + } + + backup(backSlashCnt); + return '\\'; + } + } + catch(java.io.IOException e) + { + if (backSlashCnt > 1) + backup(backSlashCnt); + + return '\\'; + } + + UpdateLineColumn(c); + backSlashCnt++; + } + + // Here, we have seen an odd number of backslash's followed by a 'u' + try + { + while ((c = ReadByte()) == 'u') + ++column; + + buffer[bufpos] = c = (char)(hexval(c) << 12 | + hexval(ReadByte()) << 8 | + hexval(ReadByte()) << 4 | + hexval(ReadByte())); + + column += 4; + } + catch(java.io.IOException e) + { + throw new Error("Invalid escape character at line " + line + + " column " + column + "."); + } + + if (backSlashCnt == 1) + return c; + else + { + backup(backSlashCnt - 1); + return '\\'; + } + } + else + { + UpdateLineColumn(c); + return (c); + } + } + + /** + * @deprecated + * @see #getEndColumn + */ + + public final int getColumn() { + return bufcolumn[bufpos]; + } + + /** + * @deprecated + * @see #getEndLine + */ + + public final int getLine() { + return bufline[bufpos]; + } + + public final int getEndColumn() { + return bufcolumn[bufpos]; + } + + public final int getEndLine() { + return bufline[bufpos]; + } + + public final int getBeginColumn() { + return bufcolumn[tokenBegin]; + } + + public final int getBeginLine() { + return bufline[tokenBegin]; + } + + public final void backup(int amount) { + + inBuf += amount; + if ((bufpos -= amount) < 0) + bufpos += bufsize; + } + + public JavaCharStream(java.io.Reader dstream, + int startline, int startcolumn, int buffersize) + { + inputStream = dstream; + line = startline; + column = startcolumn - 1; + + available = bufsize = buffersize; + buffer = new char[buffersize]; + bufline = new int[buffersize]; + bufcolumn = new int[buffersize]; + nextCharBuf = new char[4096]; + } + + public JavaCharStream(java.io.Reader dstream, + int startline, int startcolumn) + { + this(dstream, startline, startcolumn, 4096); + } + + public JavaCharStream(java.io.Reader dstream) + { + this(dstream, 1, 1, 4096); + } + public void ReInit(java.io.Reader dstream, + int startline, int startcolumn, int buffersize) + { + inputStream = dstream; + line = startline; + column = startcolumn - 1; + + if (buffer == null || buffersize != buffer.length) + { + available = bufsize = buffersize; + buffer = new char[buffersize]; + bufline = new int[buffersize]; + bufcolumn = new int[buffersize]; + nextCharBuf = new char[4096]; + } + prevCharIsLF = prevCharIsCR = false; + tokenBegin = inBuf = maxNextCharInd = 0; + nextCharInd = bufpos = -1; + } + + public void ReInit(java.io.Reader dstream, + int startline, int startcolumn) + { + ReInit(dstream, startline, startcolumn, 4096); + } + + public void ReInit(java.io.Reader dstream) + { + ReInit(dstream, 1, 1, 4096); + } + public JavaCharStream(java.io.InputStream dstream, int startline, + int startcolumn, int buffersize) + { + this(new java.io.InputStreamReader(dstream), startline, startcolumn, 4096); + } + + public JavaCharStream(java.io.InputStream dstream, int startline, + int startcolumn) + { + this(dstream, startline, startcolumn, 4096); + } + + public JavaCharStream(java.io.InputStream dstream) + { + this(dstream, 1, 1, 4096); + } + + public void ReInit(java.io.InputStream dstream, int startline, + int startcolumn, int buffersize) + { + ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, 4096); + } + public void ReInit(java.io.InputStream dstream, int startline, + int startcolumn) + { + ReInit(dstream, startline, startcolumn, 4096); + } + public void ReInit(java.io.InputStream dstream) + { + ReInit(dstream, 1, 1, 4096); + } + + public final String GetImage() + { + if (bufpos >= tokenBegin) + return new String(buffer, tokenBegin, bufpos - tokenBegin + 1); + else + return new String(buffer, tokenBegin, bufsize - tokenBegin) + + new String(buffer, 0, bufpos + 1); + } + + public final char[] GetSuffix(int len) + { + char[] ret = new char[len]; + + if ((bufpos + 1) >= len) + System.arraycopy(buffer, bufpos - len + 1, ret, 0, len); + else + { + System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0, + len - bufpos - 1); + System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1); + } + + return ret; + } + + public void Done() + { + nextCharBuf = null; + buffer = null; + bufline = null; + bufcolumn = null; + } + + /** + * Method to adjust line and column numbers for the start of a token.
+ */ + public void adjustBeginLineColumn(int newLine, int newCol) + { + int start = tokenBegin; + int len; + + if (bufpos >= tokenBegin) + { + len = bufpos - tokenBegin + inBuf + 1; + } + else + { + len = bufsize - tokenBegin + bufpos + 1 + inBuf; + } + + int i = 0, j = 0, k = 0; + int nextColDiff = 0, columnDiff = 0; + + while (i < len && + bufline[j = start % bufsize] == bufline[k = ++start % bufsize]) + { + bufline[j] = newLine; + nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j]; + bufcolumn[j] = newCol + columnDiff; + columnDiff = nextColDiff; + i++; + } + + if (i < len) + { + bufline[j] = newLine++; + bufcolumn[j] = newCol + columnDiff; + + while (i++ < len) + { + if (bufline[j = start % bufsize] != bufline[++start % bufsize]) + bufline[j] = newLine++; + else + bufline[j] = newLine; + } + } + + line = bufline[j]; + column = bufcolumn[j]; + } + +} diff --git a/src/main/java/com/lowagie/text/pdf/codec/postscript/MetaDoPS.java b/src/main/java/com/lowagie/text/pdf/codec/postscript/MetaDoPS.java new file mode 100644 index 0000000..a160e6b --- /dev/null +++ b/src/main/java/com/lowagie/text/pdf/codec/postscript/MetaDoPS.java @@ -0,0 +1,98 @@ +/* + * $Id: MetaDoPS.java,v 1.4 2006/04/22 16:56:39 psoares33 Exp $ + * $Name: $ + * + * Copyright 2001, 2002 Paulo Soares + * + * The contents of this file are subject to the Mozilla Public License Version 1.1 + * (the "License"); you may not use this file except in compliance with the License. + * You may obtain a copy of the License at http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the License. + * + * The Original Code is 'iText, a free JAVA-PDF library'. + * + * The Initial Developer of the Original Code is Bruno Lowagie. Portions created by + * the Initial Developer are Copyright (C) 1999, 2000, 2001, 2002 by Bruno Lowagie. + * All Rights Reserved. + * Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer + * are Copyright (C) 2000, 2001, 2002 by Paulo Soares. All Rights Reserved. + * + * Contributor(s): all the names of the contributors are added in the source code + * where applicable. + * + * Alternatively, the contents of this file may be used under the terms of the + * LGPL license (the "GNU LIBRARY GENERAL PUBLIC LICENSE"), in which case the + * provisions of LGPL are applicable instead of those above. If you wish to + * allow use of your version of this file only under the terms of the LGPL + * License and not to allow others to use your version of this file under + * the MPL, indicate your decision by deleting the provisions above and + * replace them with the notice and other provisions required by the LGPL. + * If you do not delete the provisions above, a recipient may use your version + * of this file under either the MPL or the GNU LIBRARY GENERAL PUBLIC LICENSE. + * + * This library is free software; you can redistribute it and/or modify it + * under the terms of the MPL as stated above or under the terms of the GNU + * Library General Public License as published by the Free Software Foundation; + * either version 2 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Library general Public License for more + * details. + * + * If you didn't download this code from the following link, you should check if + * you aren't using an obsolete version: + * http://www.lowagie.com/iText/ + */ + +package com.lowagie.text.pdf.codec.postscript; + +import java.io.*; +import java.awt.*; +import com.lowagie.text.*; +import com.lowagie.text.pdf.*; + +public class MetaDoPS { + + public PdfContentByte cb; + InputStream in; + int left; + int top; + int right; + int bottom; + int inch; + + public MetaDoPS(InputStream in, PdfContentByte cb) { + this.cb = cb; + this.in = in; + } + + public void readAll() throws IOException, DocumentException { + + cb.saveState(); + java.awt.Graphics2D g2 = cb.createGraphicsShapes(PageSize.A4. + width(), PageSize.A4.height()); + try { + PAContext context = new PAContext( (Graphics2D) g2, + new Dimension( (int) PageSize.A4.width(), + (int) PageSize.A4.height())); + context.draw(in); +// context.draw(new BufferedInputStream(in)); + // ( (Graphics2D) backBuffer.getGraphics()).dispose(); + in.close(); + } + catch (IOException ex) { + ex.printStackTrace(); + } + catch (PainterException ex) { + ex.printStackTrace(); + } + g2.dispose(); + cb.restoreState(); + + } + +} diff --git a/src/main/java/com/lowagie/text/pdf/codec/postscript/PACommand.java b/src/main/java/com/lowagie/text/pdf/codec/postscript/PACommand.java new file mode 100644 index 0000000..91b2e18 --- /dev/null +++ b/src/main/java/com/lowagie/text/pdf/codec/postscript/PACommand.java @@ -0,0 +1,19 @@ +/* + * Copyright 1998 by Sun Microsystems, Inc., + * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A. + * All rights reserved. + * + * This software is the confidential and proprietary information + * of Sun Microsystems, Inc. ("Confidential Information"). You + * shall not disclose such Confidential Information and shall use + * it only in accordance with the terms of the license agreement + * you entered into with Sun. + */ + +package com.lowagie.text.pdf.codec.postscript; + +public interface PACommand { + + public void execute(PAContext context) throws PainterException; + +} diff --git a/src/main/java/com/lowagie/text/pdf/codec/postscript/PAContext.java b/src/main/java/com/lowagie/text/pdf/codec/postscript/PAContext.java new file mode 100644 index 0000000..863d82a --- /dev/null +++ b/src/main/java/com/lowagie/text/pdf/codec/postscript/PAContext.java @@ -0,0 +1,2772 @@ +/* + * Copyright 1998 by Sun Microsystems, Inc., + * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A. + * All rights reserved. + * + * This software is the confidential and proprietary information + * of Sun Microsystems, Inc. ("Confidential Information"). You + * shall not disclose such Confidential Information and shall use + * it only in accordance with the terms of the license agreement + * you entered into with Sun. + */ + +package com.lowagie.text.pdf.codec.postscript; + +import java.util.*; +import java.io.*; +import java.awt.*; +import java.awt.geom.*; +import com.lowagie.text.pdf.PdfGraphics2D; +import com.lowagie.text.pdf.PdfContentByte; +import com.lowagie.text.pdf.PdfName; +import com.lowagie.text.*; +import com.lowagie.text.pdf.RandomAccessFileOrArray; + +public class PAContext { + + public PAPencil pencil; + public Stack dictionaries; + public Stack operands; + public PAEngine engine; + PAParser poorscript = null; + protected Random randomNumberGenerator; + InputStream is=null; + + protected Object lastUnknownIdentifier; + public static boolean IgnoreUnknownCommands = false; + public static boolean DebugExecution = false; + + public PAContext(Component component) { + this(new PAPencil(component)); + } + + public PAContext(Graphics2D g, Dimension size) { + this(new PAPencil(g, size)); + } + + public PAContext(PAPencil pencil) { + super(); + this.pencil = pencil; + this.dictionaries = new Stack(); + this.operands = new Stack(); + this.engine = new PAEngine(this); + HashMap systemDict = this.constructSystemDict(); + this.dictionaries.push(systemDict); + HashMap globalDict = this.constructGlobalDict(); + this.dictionaries.push(globalDict); + HashMap userDict = this.constructUserDict(); + systemDict.put("userdict", userDict); + this.dictionaries.push(userDict); + this.randomNumberGenerator = new Random(); + this.lastUnknownIdentifier = null; + } + + /** + * draw + * + * @param inputStream InputStream + * @throws PainterException + */ + public void draw(InputStream inputStream) throws PainterException { + try { + String filename="init.ps"; +// poorscript = new PAParser(new NamedInputStream(PAContext.class.getResourceAsStream(filename),filename)); + InputStream inpstr=PAContext.class.getResourceAsStream(filename); + poorscript = new PAParser(inpstr); + poorscript.parse(this); + try { + inpstr.close(); + } + catch (IOException ex) { + ex.printStackTrace(); + } +// poorscript.enable_tracing(); +// poorscript.token_source.setDebugStream(System.err); +// byte[] b=null; +// try { +// b = RandomAccessFileOrArray.InputStreamToArray(inputStream); +// } +// catch (IOException ex) { +// ex.printStackTrace(); +// } +// ByteArrayInputStream bar=new ByteArrayInputStream(b); +// is = bar; + poorscript.ReInit(inputStream); + poorscript.parse(this); + // pencil.graphics.dispose(); + } + catch (ParseException e) { + e.printStackTrace(); + throw new PainterException(e.toString()); + } + } + + + + public Object getLastUnknownIdentifier() { + return this.lastUnknownIdentifier; + } + + public double[] popNumberOperands(int n) throws PainterException { + double[] result = new double[n]; + Object objectValue; + double doubleValue; + + for (int i = n - 1; i >= 0; i--) { + try { + objectValue = this.operands.pop(); + } + catch (EmptyStackException e) { + throw new PainterException("Operand stack is empty poping " + n + + " number operands"); + } + if (objectValue instanceof Number) { + doubleValue = ( (Number) objectValue).doubleValue(); + } + else { + throw new PainterException("Number expected on operand stack poping " + + n + " number operands, found " + + objectValue.getClass().getName()); + } + result[i] = doubleValue; + } + return result; + } + + public Object[] popOperands(int n) throws PainterException { + Object[] result = new Object[n]; + Object objectValue; + + for (int i = n - 1; i >= 0; i--) { + try { + objectValue = this.operands.pop(); + } + catch (EmptyStackException e) { + throw new PainterException("Operand stack is empty poping " + n + + " operands"); + } + result[i] = objectValue; + } + return result; + } + + public Object peekOperand() throws PainterException { + Object objectValue; + + try { + objectValue = this.operands.peek(); + } + catch (EmptyStackException e) { + throw new PainterException("Operand stack is empty peeking operand"); + } + return objectValue; + } + + public Object findIdentifier(Object identifier) { + Object result = null; + int i, n; + + n = this.dictionaries.size(); + i = n - 1; + while (i >= 0 && result == null) { + HashMap dictionary = (HashMap)this.dictionaries.elementAt(i); + result = dictionary.get(identifier); + i--; + } + if (result == null) { + this.lastUnknownIdentifier = identifier; + } + return result; + } + + public Object findDictionary(Object identifier) { + Object result = null; + HashMap dictionary = null; + int i, n; + + n = this.dictionaries.size(); + i = n - 1; + while (i >= 0 && result == null) { + dictionary = (HashMap)this.dictionaries.elementAt(i); + result = dictionary.get(identifier); + i--; + } + if (result == null) { + return result; + } + else { + return dictionary; + } + } + + public void collectArray() throws PainterException { + ArrayList result; + Object objectValue; + int i, n; + boolean found = false; + + n = this.operands.size(); + for (i = n - 1; i >= 0; i--) { + objectValue = this.operands.elementAt(i); + if (objectValue instanceof PAToken && + ( (PAToken) objectValue).type == PAToken.START_ARRAY) { + found = true; + break; + } + } + if (!found) { + throw new PainterException("No array was started"); + } + result = new ArrayList(n - i - 1); + for (int j = 0; j < n - i - 1; j++) { + result.add(null); + } + for (int j = n - 1; j > i; j--) { + try { + objectValue = this.operands.pop(); + } + catch (EmptyStackException e) { + throw new PainterException( + "Operand stack is empty collecting array elements"); + } + result.set(j - i - 1, objectValue); + } + try { + this.operands.pop(); // the start array mark itself + } + catch (EmptyStackException e) { + throw new PainterException( + "Operand stack is empty removing begin array mark"); + } + this.operands.push(result); + } + + public void collectDict() throws PainterException { + HashMap result; // = new HashMap(); + Object objectValue; + int i, n; + boolean found = false; + + n = this.operands.size(); + for (i = n - 1; i >= 0; i--) { + objectValue = this.operands.elementAt(i); + if (objectValue instanceof PAToken && + ( (PAToken) objectValue).type == PAToken.START_DICT) { + found = true; + break; + } + } + if (!found) { + throw new PainterException("No dict was started"); + } +// result = new ArrayList(n - i - 1); + result = new HashMap(); +// for (int j = 0; j < n - i - 1; j++) { +// result.add(null); +// } + for (int j = n - 1; j > i; j -= 2) { + Object targetValue; + try { + targetValue = this.operands.pop(); + objectValue = this.operands.pop(); + } + catch (EmptyStackException e) { + throw new PainterException( + "Operand stack is empty collecting hashmap elements"); + } + result.put(objectValue, targetValue); + } + try { + this.operands.pop(); // the start array mark itself + } + catch (EmptyStackException e) { + throw new PainterException( + "Operand stack is empty removing begin array mark"); + } + this.operands.push(result); + } + + protected HashMap constructGlobalDict() { + HashMap globalDict = new HashMap(); + return globalDict; + } + + protected HashMap constructUserDict() { + HashMap userDict = new HashMap(); + + return userDict; + } + + public static void main(String[] args) { + javax.swing.JFrame jf = new javax.swing.JFrame(); + jf.setVisible(true); + jf.setDefaultCloseOperation(jf.DISPOSE_ON_CLOSE); + PAContext pac = new PAContext(new PAPencil(jf)); + HashMap hm = (HashMap) pac.findDictionary("systemdict"); + Iterator it = new TreeSet(hm.keySet()).iterator(); + while (it.hasNext()) { + + String obname = it.next().toString(); + Object ob = hm.get(obname); + String typname = ob.getClass().getName(); + System.out.println(obname + ":" + typname); + } + System.exit(0); + } + + protected HashMap constructSystemDict() { + HashMap systemDict = new HashMap(); + + // newpath + systemDict.put("newpath", new PACommand() { + public void execute(PAContext context) throws PainterException { + context.pencil.newpath(); + } + }); + + // moveto + systemDict.put("moveto", new PACommand() { + public void execute(PAContext context) throws PainterException { + double data[]; + data = context.popNumberOperands(2); + context.pencil.moveto(data[0], data[1]); + } + }); + + // rmoveto + systemDict.put("rmoveto", new PACommand() { + public void execute(PAContext context) throws PainterException { + double data[]; + + data = context.popNumberOperands(2); + context.pencil.rmoveto(data[0], data[1]); + } + }); + + // lineto + systemDict.put("lineto", new PACommand() { + public void execute(PAContext context) throws PainterException { + double data[]; + + data = context.popNumberOperands(2); + context.pencil.lineto(data[0], data[1]); + } + }); + + // rlineto + systemDict.put("rlineto", new PACommand() { + public void execute(PAContext context) throws PainterException { + double data[]; + + data = context.popNumberOperands(2); + context.pencil.rlineto(data[0], data[1]); + } + }); + + // arc + systemDict.put("arc", new PACommand() { + public void execute(PAContext context) throws PainterException { + double data[]; + + data = context.popNumberOperands(5); + context.pencil.arc(data[0], data[1], data[2], data[3], data[4]); + } + }); + + // arcn + systemDict.put("arcn", new PACommand() { + public void execute(PAContext context) throws PainterException { + double data[]; + + data = context.popNumberOperands(5); + context.pencil.arcn(data[0], data[1], data[2], data[3], data[4]); + } + }); + + // curveto + systemDict.put("curveto", new PACommand() { + public void execute(PAContext context) throws PainterException { + double data[]; + + data = context.popNumberOperands(6); + context.pencil.curveto(data[0], data[1], data[2], data[3], data[4], + data[5]); + } + }); + + // rcurveto + systemDict.put("rcurveto", new PACommand() { + public void execute(PAContext context) throws PainterException { + double data[]; + + data = context.popNumberOperands(6); + context.pencil.rcurveto(data[0], data[1], data[2], data[3], data[4], + data[5]); + } + }); + + // closepath + systemDict.put("closepath", new PACommand() { + public void execute(PAContext context) throws PainterException { + context.pencil.closepath(); + } + }); + + // gsave + systemDict.put("gsave", new PACommand() { + public void execute(PAContext context) throws PainterException { + context.pencil.gsave(); + } + }); + + // grestore + systemDict.put("grestore", new PACommand() { + public void execute(PAContext context) throws PainterException { + context.pencil.grestore(); + } + }); + + // translate + systemDict.put("translate", new PACommand() { + public void execute(PAContext context) throws PainterException { + if (context.peekOperand() instanceof Number) { + double data[]; + AffineTransform at = new AffineTransform(); + AffineTransform ctm = context.pencil.graphics.getTransform(); + + data = context.popNumberOperands(2); + at.translate(data[0], data[1]); + ctm.concatenate(at); + context.pencil.graphics.setTransform(ctm); + } + else { + Object data[]; + + data = context.popOperands(3); + if (! (data[0] instanceof Number)) { + throw new PainterException("translate: wrong arguments"); + } + if (! (data[1] instanceof Number)) { + throw new PainterException("translate: wrong arguments"); + } + if (! (data[2] instanceof ArrayList)) { + throw new PainterException("translate: wrong arguments"); + } + + ArrayList array = (ArrayList) data[2]; + + if (! (array.size() == 6)) { + throw new PainterException("translate: wrong arguments"); + } + + AffineTransform at = new AffineTransform(); + + at.translate( ( (Number) data[0]).doubleValue(), + ( (Number) data[1]).doubleValue()); + + double[] entries = new double[6]; + + at.getMatrix(entries); + + for (int i = 0; i < 6; i++) { + array.set(i, new Double(entries[i])); + } + context.operands.push(array); + } + } + }); + + // rotate + systemDict.put("rotate", new PACommand() { + public void execute(PAContext context) throws PainterException { + if (context.peekOperand() instanceof Number) { + double data[]; + AffineTransform at = new AffineTransform(); + AffineTransform ctm = context.pencil.graphics.getTransform(); + + data = context.popNumberOperands(1); + at.rotate(data[0] * Math.PI / 180.0d); + ctm.concatenate(at); + context.pencil.graphics.setTransform(ctm); + } + else { + Object data[]; + AffineTransform at = new AffineTransform(); + + data = context.popOperands(2); + if (! (data[0] instanceof Number)) { + throw new PainterException("rotate: wrong arguments"); + } + if (! (data[1] instanceof ArrayList)) { + throw new PainterException("rotate: wrong arguments"); + } + + ArrayList array = (ArrayList) data[1]; + + if (! (array.size() == 6)) { + throw new PainterException("rotate: wrong arguments"); + } + + at.rotate( ( (Number) data[0]).doubleValue()); + + double[] entries = new double[6]; + + at.getMatrix(entries); + + for (int i = 0; i < 6; i++) { + array.set(i, new Double(entries[i])); + } + context.operands.push(array); + } + } + }); + + // scale + systemDict.put("scale", new PACommand() { + public void execute(PAContext context) throws PainterException { + if (context.peekOperand() instanceof Number) { + double data[]; + AffineTransform at = new AffineTransform(); + AffineTransform ctm = context.pencil.graphics.getTransform(); + + data = context.popNumberOperands(2); + at.scale(data[0], data[1]); + ctm.concatenate(at); + context.pencil.graphics.setTransform(ctm); + } + else { + Object data[]; + + data = context.popOperands(3); + if (! (data[0] instanceof Number)) { + throw new PainterException("scale: wrong arguments"); + } + if (! (data[1] instanceof Number)) { + throw new PainterException("scale: wrong arguments"); + } + if (! (data[2] instanceof ArrayList)) { + throw new PainterException("scale: wrong arguments"); + } + + ArrayList array = (ArrayList) data[2]; + + double[] entries = new double[6]; + + if (! (array.size() == 6)) { + throw new PainterException("scale: wrong arguments"); + } + + entries[0] = ( (Number) data[0]).doubleValue(); + entries[1] = 0.0d; + entries[2] = 0.0d; + entries[3] = ( (Number) data[1]).doubleValue(); + entries[4] = 0.0d; + entries[5] = 0.0d; + + for (int i = 0; i < 6; i++) { + array.set(i, new Double(entries[i])); + } + context.operands.push(array); + } + } + }); + // currentmatrix + systemDict.put("currentmatrix", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + data = context.popOperands(1); + if (! (data[0] instanceof ArrayList)) { + throw new PainterException("currentmatrix: wrong argument"); + } + ArrayList array = (ArrayList) data[0]; + + double[] entries = new double[6]; + + if (! (array.size() == 6)) { + throw new PainterException("currentmatrix: wrong arguments"); + } + + + AffineTransform ctm = context.pencil.graphics.getTransform(); + ctm.getMatrix(entries); + + for (int i = 0; i < 6; i++) { + array.set(i, new Double(entries[i])); + } + context.operands.push(array); + } + }); + + // setmatrix + systemDict.put("setmatrix", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + data = context.popOperands(1); + if (! (data[0] instanceof ArrayList)) { + throw new PainterException("setmatrix: wrong argument"); + } + ArrayList array = (ArrayList) data[0]; + + double[] entries = new double[6]; + + if (! (array.size() == 6)) { + throw new PainterException("setmatrix: wrong arguments"); + } + entries[0] = ((Number)array.get(0)).doubleValue(); + entries[1] = ((Number)array.get(1)).doubleValue(); + entries[2] = ((Number)array.get(2)).doubleValue(); + entries[3] = ((Number)array.get(3)).doubleValue(); + entries[4] = ((Number)array.get(4)).doubleValue(); + entries[5] = ((Number)array.get(5)).doubleValue(); + + AffineTransform at = new AffineTransform(entries); + context.pencil.graphics.setTransform(at); + } + }); + + // stroke + systemDict.put("stroke", new PACommand() { + public void execute(PAContext context) throws PainterException { + context.pencil.stroke(); + } + }); + + // fill + systemDict.put("fill", new PACommand() { + public void execute(PAContext context) throws PainterException { + context.pencil.fill(); + } + }); + + // eofill + systemDict.put("eofill", new PACommand() { + public void execute(PAContext context) throws PainterException { + context.pencil.eofill(); + } + }); + + // show + systemDict.put("show", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + + data = context.popOperands(1); + if (! (data[0] instanceof String)) { + throw new PainterException("show: wrong arguments"); + } + context.pencil.show( (String) data[0]); + } + }); + + // stringwidth + systemDict.put("stringwidth", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + float[] result; + java.awt.Font font; + + data = context.popOperands(1); + if (! (data[0] instanceof String)) { + throw new PainterException("stringwidth: wrong arguments"); + } + font = context.pencil.graphics.getFont(); + Rectangle2D rect = font.getStringBounds( (String) data[0], + context.pencil.graphics. + getFontRenderContext()); + context.operands.push(new Float(rect.getWidth())); + context.operands.push(new Float(rect.getHeight())); + } + }); + + // showpage + systemDict.put("showpage", new PACommand() { + public void execute(PAContext context) throws PainterException { + context.pencil.showpage(); + } + }); + + // findfont + systemDict.put("findfont", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + PAToken patoken; + data = context.popOperands(1); + if (! (data[0] instanceof PAToken)) { + throw new PainterException("findfont: wrong arguments"); + } + patoken = (PAToken) data[0]; + if (! (patoken.type == PAToken.KEY)) { + throw new PainterException("findfont: wrong arguments"); + } + context.operands.push(context.pencil.findFont( (String) patoken.value)); + } + }); + + // makefont + systemDict.put("makefont", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + data = context.popOperands(2); + if (! (data[0] instanceof java.awt.Font)) { + throw new PainterException("makefont: wrong arguments"); + } + if (! (data[1] instanceof ArrayList)) { + throw new PainterException("makefont: wrong arguments"); + } + // @TODO implement!!! + context.operands.push(data[0]); + } + }); + + // scalefont + systemDict.put("scalefont", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + data = context.popOperands(2); + if (! (data[0] instanceof java.awt.Font)) { + throw new PainterException("scalefont: wrong arguments"); + } + if (! (data[1] instanceof Number)) { + throw new PainterException("scalefont: wrong arguments"); + } + java.awt.Font fn=( (java.awt.Font) data[0]).deriveFont( ( (Number) + data[1]). + floatValue()); + System.out.println("Fonthoehe:"+fn.getSize2D()); + context.operands.push(fn ); + } + }); + + // setfont + systemDict.put("setfont", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + data = context.popOperands(1); + if (! (data[0] instanceof java.awt.Font)) { + throw new PainterException("setfont: wrong arguments"); + } + java.awt.Font fn=(java.awt.Font)data[0]; + System.out.println("Fonthoehe:"+fn.getSize2D()); + /** + * @todo two times the same? + */ + context.pencil.graphics.setFont( fn); + context.pencil.state.font=fn; + } + }); + + // def + systemDict.put("def", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + PAToken patoken; + data = context.popOperands(2); + if (! (data[0] instanceof PAToken)) { + throw new PainterException("def: wrong arguments"); + } + patoken = (PAToken) data[0]; + if (! (patoken.type == PAToken.KEY)) { + throw new PainterException("def: wrong arguments"); + } + try { + ( (HashMap) context.dictionaries.peek()).put(patoken.value, data[1]); + } + catch (EmptyStackException e) { + throw new PainterException(e.toString()); + } + } + }); + + // bind + systemDict.put("bind", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + PAToken patoken; + data = context.popOperands(1); + if (! (data[0] instanceof PAToken)) { + throw new PainterException("bind: wrong arguments, not PAToken"); + } + patoken = (PAToken) data[0]; + if (! (patoken.type == PAToken.PROCEDURE)) { + throw new PainterException("bind: wrong arguments, not Procedure " + + patoken.value); + } + context.engine.bindProcedure(patoken); + context.operands.push(patoken); + } + }); + + // mul + systemDict.put("mul", new PACommand() { + public void execute(PAContext context) throws PainterException { + double data[]; + + data = context.popNumberOperands(2); + context.operands.push(new Double(data[0] * data[1])); + } + }); + + // div + systemDict.put("div", new PACommand() { + public void execute(PAContext context) throws PainterException { + double data[]; + + data = context.popNumberOperands(2); + context.operands.push(new Double(data[0] / data[1])); + } + }); + + // mod + systemDict.put("mod", new PACommand() { + public void execute(PAContext context) throws PainterException { + double data[]; + + data = context.popNumberOperands(2); + int a, b, m; + a = (int) data[0]; + b = (int) data[1]; + m = a % b; + context.operands.push(new Integer(m)); + } + }); + + // add + systemDict.put("add", new PACommand() { + public void execute(PAContext context) throws PainterException { + double data[]; + + data = context.popNumberOperands(2); + context.operands.push(new Double(data[0] + data[1])); + } + }); + + // neg + systemDict.put("neg", new PACommand() { + public void execute(PAContext context) throws PainterException { + double data[]; + data = context.popNumberOperands(1); + context.operands.push(new Double( -data[0])); + } + }); + // ceiling + systemDict.put("ceiling", new PACommand() { + public void execute(PAContext context) throws PainterException { + double data[]; + data = context.popNumberOperands(1); + context.operands.push(new Double(Math.ceil(data[0]))); + } + }); + // sub + systemDict.put("sub", new PACommand() { + public void execute(PAContext context) throws PainterException { + double data[]; + data = context.popNumberOperands(2); + context.operands.push(new Double(data[0] - data[1])); + } + }); + + // atan + systemDict.put("atan", new PACommand() { + public void execute(PAContext context) throws PainterException { + double data[]; + + data = context.popNumberOperands(2); + context.operands.push(new Double(Math.atan2(data[0], data[1]))); + } + }); + + // sin + systemDict.put("sin", new PACommand() { + public void execute(PAContext context) throws PainterException { + double data[]; + + data = context.popNumberOperands(1); + context.operands.push(new Double(Math.sin(data[0] * Math.PI / 180.0))); + } + }); + + // cos + systemDict.put("cos", new PACommand() { + public void execute(PAContext context) throws PainterException { + double data[]; + + data = context.popNumberOperands(1); + context.operands.push(new Double(Math.cos(data[0] * Math.PI / 180.0))); + } + }); + + // sqrt + systemDict.put("sqrt", new PACommand() { + public void execute(PAContext context) throws PainterException { + double data[]; + data = context.popNumberOperands(1); + context.operands.push(new Double(Math.sqrt(data[0]))); + } + }); + // ln + systemDict.put("log", new PACommand() { + public void execute(PAContext context) throws PainterException { + double data[]; + data = context.popNumberOperands(1); + context.operands.push(new Double(Math.log(data[0]))); + } + }); + // exp + systemDict.put("exp", new PACommand() { + public void execute(PAContext context) throws PainterException { + double data[]; + data = context.popNumberOperands(2); + context.operands.push(new Double(Math.pow(data[0], data[1]))); + } + }); + + // exch + systemDict.put("exch", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + + data = context.popOperands(2); + context.operands.push(data[1]); + context.operands.push(data[0]); + } + }); + + // dup + systemDict.put("dup", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + + data = context.popOperands(1); + context.operands.push(data[0]); + context.operands.push(data[0]); + } + }); + + // roll + systemDict.put("roll", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + Object rollData[]; + + data = context.popOperands(2); + if (! (data[0] instanceof Number)) { + throw new PainterException("roll: wrong arguments"); + } + if (! (data[1] instanceof Number)) { + throw new PainterException("roll: wrong arguments"); + } + int numberOfElements, numberOfPositions, i; + + numberOfElements = ( (Number) data[0]).intValue(); + numberOfPositions = ( (Number) data[1]).intValue(); + + if (numberOfPositions == 0 || numberOfElements <= 0) { + return; + } + + rollData = context.popOperands(numberOfElements); + + if (numberOfPositions < 0) { + numberOfPositions = -numberOfPositions; + numberOfPositions = numberOfPositions % numberOfElements; + + // downward roll + for (i = numberOfPositions; i < numberOfElements; i++) { + context.operands.push(rollData[i]); + } + for (i = 0; i < numberOfPositions; i++) { + context.operands.push(rollData[i]); + } + } + else { + numberOfPositions = numberOfPositions % numberOfElements; + + // upward roll + for (i = numberOfElements - numberOfPositions; i < numberOfElements; + i++) { + context.operands.push(rollData[i]); + } + for (i = 0; i < numberOfElements - numberOfPositions; i++) { + context.operands.push(rollData[i]); + } + } + } + }); + + // pop + systemDict.put("pop", new PACommand() { + public void execute(PAContext context) throws PainterException { + context.popOperands(1); + } + }); + + // index + systemDict.put("index", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + data = context.popOperands(1); + if (! (data[0] instanceof Number)) { + throw new PainterException("index: wrong arguments"); + } + int index = ( (Number) data[0]).intValue(); + try { + context.operands.push(context.operands.elementAt(index)); + } + catch (ArrayIndexOutOfBoundsException e) { + throw new PainterException(e.toString()); + } + } + }); + + // mark + systemDict.put("mark", new PACommand() { + public void execute(PAContext context) throws PainterException { + context.operands.push(new PAToken(null, PAToken.MARK)); + } + }); + + // cvx + systemDict.put("cvx", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data; + data = context.operands.pop(); + ArrayList ar = (ArrayList) data; + Stack stack = new Stack(); + for (int i = ar.size() - 1; i >= 0; i--) { + stack.add(ar.get(i)); + } + PAToken patoken = new PAToken(stack, PAToken.PROCEDURE); +// patoken.type=PAToken.PROCEDURE; + context.operands.push(patoken); + } + }); + // cleartomark + systemDict.put("cleartomark", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data; + boolean finished = false; + + while (!finished) { + try { + data = context.operands.pop(); + if (data instanceof PAToken) { + if ( ( (PAToken) data).type == PAToken.MARK) { + finished = true; + } + } + } + catch (EmptyStackException e) { + throw new PainterException(e.toString()); + } + } + } + }); + + // copy + systemDict.put("copy", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + data = context.popOperands(2); + + // decide if it's a simple copy or a composite object copy + if ( (data[0] instanceof PAToken) && (data[1] instanceof PAToken)) { + // composite object copy + if ( ( (PAToken) data[0]).type == ( (PAToken) data[1]).type) { + // our tokens are immutable so a copy is easy + context.operands.push(data[0]); + context.operands.push(data[0]); + } + else { + throw new PainterException( + "copy operation failed because composite objects on stack are not of same type"); + } + } + else { + // restore first arg, we're not interested in it in this simple case + context.operands.push(data[0]); + + if (data[1] instanceof Number) { + int index = ( (Number) data[1]).intValue(); + int i, n; + n = context.operands.size(); + Object[] copyData = new Object[index]; + for (i = n - index; i < n; i++) { + try { + copyData[i - n + index] = context.operands.elementAt(i); + } + catch (ArrayIndexOutOfBoundsException e) { + throw new PainterException(e.toString()); + } + } + for (i = 0; i < index; i++) { + context.operands.push(copyData[i]); + } + } + else { + throw new PainterException("I expect a number on stack, dude"); + } + } + } + }); + + // setgray + systemDict.put("setgray", new PACommand() { + public void execute(PAContext context) throws PainterException { + double data[]; + + data = context.popNumberOperands(1); + context.pencil.graphics.setPaint(new Color( (float) data[0], + (float) data[0], (float) data[0])); + } + }); + + // setrgbcolor + systemDict.put("setrgbcolor", new PACommand() { + public void execute(PAContext context) throws PainterException { + double data[]; + + data = context.popNumberOperands(3); + float[] fv = new float[3]; + fv[0] = (float) Math.max(Math.min(data[0], 1.0d), 0.0d); + fv[1] = (float) Math.max(Math.min(data[1], 1.0d), 0.0d); + fv[2] = (float) Math.max(Math.min(data[2], 1.0d), 0.0d); + context.pencil.graphics.setPaint(new Color(fv[0], fv[1], fv[2])); + } + }); + + // currentrgbcolor +systemDict.put("currentrgbcolor", new PACommand() { + public void execute(PAContext context) throws PainterException { + Color cl=context.pencil.graphics.getColor(); + float[] fv = cl.getRGBComponents(null); + context.operands.push(new Float(fv[0])); + context.operands.push(new Float(fv[1])); + context.operands.push(new Float(fv[2])); + } +}); + + + // PENDING(uweh): color stuff still shaky + // sethsbcolor + systemDict.put("sethsbcolor", new PACommand() { + public void execute(PAContext context) throws PainterException { + double data[]; + data = context.popNumberOperands(3); + float[] fv = new float[3]; + fv[0] = (float) Math.max(Math.min(data[0], 1.0d), 0.0d); + fv[1] = (float) Math.max(Math.min(data[1], 1.0d), 0.0d); + fv[2] = (float) Math.max(Math.min(data[2], 1.0d), 0.0d); + context.pencil.graphics.setPaint(new Color(fv[0], fv[1], fv[2])); + } + }); + + // PENDING(uweh): I have to convert these puppies myself to rgb ? + // setcmykcolor + systemDict.put("setcmykcolor", new PACommand() { + public void execute(PAContext context) throws PainterException { + double data[]; + int rd, gr, bl; + + data = context.popNumberOperands(4); + float[] fv = new float[4]; + fv[0] = (float) data[0]; + fv[1] = (float) data[1]; + fv[2] = (float) data[2]; + fv[3] = (float) data[3]; + rd = (int) (255 * Math.max(0, 1 - fv[0] - fv[3])); + gr = (int) (255 * Math.max(0, 1 - fv[1] - fv[3])); + bl = (int) (255 * Math.max(0, 1 - fv[2] - fv[3])); + context.pencil.graphics.setPaint(new Color(rd, gr, bl)); + } + }); + + // setlinewidth + systemDict.put("setlinewidth", new PACommand() { + private double minLineWidth(double w, AffineTransform at) { + double matrix[] = new double[4]; + at.getMatrix(matrix); + double scale = matrix[0] * matrix[3] - matrix[1] * matrix[2]; + double minlw = .25 / Math.sqrt(Math.abs(scale)); + if (w < minlw) { + w = minlw; + } + return w; + } + + public void execute(PAContext context) throws PainterException { + double data[]; + BasicStroke newStroke; + Stroke oldStroke = context.pencil.graphics.getStroke(); + data = context.popNumberOperands(1); + data[0] = this.minLineWidth(data[0], + context.pencil.graphics.getTransform()); + if (oldStroke instanceof BasicStroke) { + newStroke = new BasicStroke( (float) data[0], + ( (BasicStroke) oldStroke).getEndCap(), + ( (BasicStroke) oldStroke).getLineJoin(), + ( (BasicStroke) oldStroke).getMiterLimit(), + ( (BasicStroke) oldStroke).getDashArray(), + ( (BasicStroke) oldStroke).getDashPhase()); + } + else { + newStroke = new BasicStroke( (float) data[0], BasicStroke.CAP_ROUND, + BasicStroke.JOIN_ROUND); + } + /** + * @todo two times the same? + */ + context.pencil.graphics.setStroke(newStroke); +// context.pencil.state.stroke=newStroke; + } + }); + + // setlinecap + systemDict.put("setlinecap", new PACommand() { + public void execute(PAContext context) throws PainterException { + double data[]; + BasicStroke newStroke; + Stroke oldStroke = context.pencil.graphics.getStroke(); + data = context.popNumberOperands(1); + if (oldStroke instanceof BasicStroke) { + newStroke = new BasicStroke( ( (BasicStroke) oldStroke).getLineWidth(), + (int) data[0], + ( (BasicStroke) oldStroke).getLineJoin(), + ( (BasicStroke) oldStroke).getMiterLimit(), + ( (BasicStroke) oldStroke).getDashArray(), + ( (BasicStroke) oldStroke).getDashPhase()); + } + else { + newStroke = new BasicStroke(1.0f, (int) data[0], + BasicStroke.JOIN_ROUND); + } + context.pencil.graphics.setStroke(newStroke); + } + }); + + // setmiterlimit + systemDict.put("setmiterlimit", new PACommand() { + public void execute(PAContext context) throws PainterException { + double data[]; + BasicStroke newStroke; + Stroke oldStroke = context.pencil.graphics.getStroke(); + data = context.popNumberOperands(1); + if (oldStroke instanceof BasicStroke) { + newStroke = new BasicStroke( ( (BasicStroke) oldStroke).getLineWidth(), + ( (BasicStroke) oldStroke).getEndCap(), + ( (BasicStroke) oldStroke).getLineJoin(), + (float) data[0], + ( (BasicStroke) oldStroke).getDashArray(), + ( (BasicStroke) oldStroke).getDashPhase()); + } + else { + newStroke = new BasicStroke(1.0f, BasicStroke.CAP_ROUND, + BasicStroke.JOIN_ROUND, (float) data[0]); + } + context.pencil.graphics.setStroke(newStroke); + } + }); + + // setdash + systemDict.put("setdash", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + BasicStroke newStroke; + Stroke oldStroke = context.pencil.graphics.getStroke(); + data = context.popOperands(2); + if (! (data[0] instanceof ArrayList)) { + throw new PainterException("setdash: wrong arguments"); + } + if (! (data[1] instanceof Number)) { + throw new PainterException("setdash: wrong arguments"); + } + + ArrayList list = (ArrayList) data[0]; + + if (list.size() == 0) { + return; + } + float[] dashpattern = new float[list.size()]; + for (int i = 0; i < dashpattern.length; i++) { + dashpattern[i] = ( (Number) list.get(i)).floatValue(); + } + float dashoffset = ( (Number) data[1]).floatValue(); + if (oldStroke instanceof BasicStroke) { + newStroke = new BasicStroke( ( (BasicStroke) oldStroke).getLineWidth(), + ( (BasicStroke) oldStroke).getEndCap(), + ( (BasicStroke) oldStroke).getLineJoin(), + ( (BasicStroke) oldStroke).getMiterLimit(), + dashpattern, + dashoffset); + } + else { + newStroke = new BasicStroke(1.0f, BasicStroke.CAP_ROUND, + BasicStroke.JOIN_ROUND, 1.0f, dashpattern, + dashoffset); + } + context.pencil.graphics.setStroke(newStroke); + } + }); + + // setlinejoin + systemDict.put("setlinejoin", new PACommand() { + public void execute(PAContext context) throws PainterException { + double data[]; + BasicStroke newStroke; + Stroke oldStroke = context.pencil.graphics.getStroke(); + data = context.popNumberOperands(1); + if (oldStroke instanceof BasicStroke) { + newStroke = new BasicStroke( ( (BasicStroke) oldStroke).getLineWidth(), + ( (BasicStroke) oldStroke).getEndCap(), + (int) data[0], + ( (BasicStroke) oldStroke).getMiterLimit(), + ( (BasicStroke) oldStroke).getDashArray(), + ( (BasicStroke) oldStroke).getDashPhase()); + } + else { + newStroke = new BasicStroke(1.0f, BasicStroke.CAP_ROUND, (int) data[0]); + } + context.pencil.graphics.setStroke(newStroke); + } + }); + + // dumpstack + systemDict.put("dumpstack", new PACommand() { + public void execute(PAContext context) throws PainterException { + Enumeration enumx = context.operands.elements(); + System.out.println("-------------Stack--------------"); + while (enumx.hasMoreElements()) { + System.out.println(enumx.nextElement()); + } + System.out.println("--------------------------------"); + } + }); + + // for + systemDict.put("for", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + PAToken patoken; + + data = context.popOperands(4); + if (! (data[3] instanceof PAToken)) { + throw new PainterException("for: wrong arguments"); + } + if (! (data[0] instanceof Number)) { + throw new PainterException("for: wrong arguments"); + } + if (! (data[1] instanceof Number)) { + throw new PainterException("for: wrong arguments"); + } + if (! (data[2] instanceof Number)) { + throw new PainterException("for: wrong arguments"); + } + patoken = (PAToken) data[3]; + if (! (patoken.type == PAToken.PROCEDURE)) { + throw new PainterException("for: wrong arguments"); + } + int i0, i1, i2; + i0 = ( (Number) data[0]).intValue(); + i1 = ( (Number) data[1]).intValue(); + i2 = ( (Number) data[2]).intValue(); + + if (i1 > 0) { + for (int i = i0; i <= i2; i += i1) { + context.operands.push(new Integer(i)); + context.engine.process(patoken); + } + } + else { + for (int i = i0; i >= i2; i -= i1) { + context.operands.push(new Integer(i)); + context.engine.process(patoken); + } + } + } + }); + + // repeat + systemDict.put("repeat", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + PAToken patoken; + data = context.popOperands(2); + if (! (data[1] instanceof PAToken)) { + throw new PainterException("repeat: wrong arguments"); + } + if (! (data[0] instanceof Number)) { + throw new PainterException("repeat: wrong arguments"); + } + patoken = (PAToken) data[1]; + if (! (patoken.type == PAToken.PROCEDURE)) { + throw new PainterException("repeat: wrong arguments"); + } + int n = ( (Number) data[0]).intValue(); + for (int i = 0; i < n; i++) { + context.engine.process(patoken); + } + } + }); + + // true + systemDict.put("true", new PACommand() { + public void execute(PAContext context) throws PainterException { + context.operands.push(new Boolean(true)); + } + }); + + // false + systemDict.put("false", new PACommand() { + public void execute(PAContext context) throws PainterException { + context.operands.push(new Boolean(false)); + } + }); + + // lt + systemDict.put("lt", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + + data = context.popOperands(2); + if (! (data[0] instanceof Number) && ! (data[0] instanceof String)) { + throw new PainterException("lt: wrong arguments"); + } + if (data[0] instanceof Number) { + if (! (data[1] instanceof Number)) { + throw new PainterException("lt: wrong arguments"); + } + double d0, d1; + d0 = ( (Number) data[0]).doubleValue(); + d1 = ( (Number) data[1]).doubleValue(); + if (d0 < d1) { + context.operands.push(new Boolean(true)); + } + else { + context.operands.push(new Boolean(false)); + } + } + else { + if (! (data[1] instanceof String)) { + throw new PainterException("lt: wrong arguments"); + } + String s0, s1; + s0 = (String) data[0]; + s1 = (String) data[1]; + if (s0.compareTo(s1) < 0) { + context.operands.push(new Boolean(true)); + } + else { + context.operands.push(new Boolean(false)); + } + } + } + }); + + // gt + systemDict.put("gt", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + + data = context.popOperands(2); + if (! (data[0] instanceof Number) && ! (data[0] instanceof String)) { + throw new PainterException("gt: wrong arguments"); + } + if (data[0] instanceof Number) { + if (! (data[1] instanceof Number)) { + throw new PainterException("gt: wrong arguments"); + } + double d0, d1; + d0 = ( (Number) data[0]).doubleValue(); + d1 = ( (Number) data[1]).doubleValue(); + if (d0 > d1) { + context.operands.push(new Boolean(true)); + } + else { + context.operands.push(new Boolean(false)); + } + } + else { + if (! (data[1] instanceof String)) { + throw new PainterException("gt: wrong arguments"); + } + String s0, s1; + s0 = (String) data[0]; + s1 = (String) data[1]; + if (s0.compareTo(s1) > 0) { + context.operands.push(new Boolean(true)); + } + else { + context.operands.push(new Boolean(false)); + } + } + } + }); + // ge + systemDict.put("ge", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + + data = context.popOperands(2); + if (! (data[0] instanceof Number) && ! (data[0] instanceof String)) { + throw new PainterException("ge: wrong arguments"); + } + if (data[0] instanceof Number) { + if (! (data[1] instanceof Number)) { + throw new PainterException("ge: wrong arguments"); + } + double d0, d1; + d0 = ( (Number) data[0]).doubleValue(); + d1 = ( (Number) data[1]).doubleValue(); + if (d0 >= d1) { + context.operands.push(new Boolean(true)); + } + else { + context.operands.push(new Boolean(false)); + } + } + else { + if (! (data[1] instanceof String)) { + throw new PainterException("ge: wrong arguments"); + } + String s0, s1; + s0 = (String) data[0]; + s1 = (String) data[1]; + if (s0.compareTo(s1) >= 0) { + context.operands.push(new Boolean(true)); + } + else { + context.operands.push(new Boolean(false)); + } + } + } + }); + // ne + systemDict.put("ne", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + + data = context.popOperands(2); + if (! (data[0] instanceof Number) && ! (data[0] instanceof String)) { + throw new PainterException("ne: wrong arguments"); + } + if (data[0] instanceof Number) { + if (! (data[1] instanceof Number)) { + throw new PainterException("ne: wrong arguments"); + } + double d0, d1; + d0 = ( (Number) data[0]).doubleValue(); + d1 = ( (Number) data[1]).doubleValue(); + if (d0 != d1) { + context.operands.push(new Boolean(true)); + } + else { + context.operands.push(new Boolean(false)); + } + } + else { + if (! (data[1] instanceof String)) { + throw new PainterException("ne: wrong arguments"); + } + String s0, s1; + s0 = (String) data[0]; + s1 = (String) data[1]; + if (s0.equals(s1)) { + context.operands.push(new Boolean(false)); + } + else { + context.operands.push(new Boolean(true)); + } + } + } + }); + + // eq + systemDict.put("eq", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + + data = context.popOperands(2); + if (! (data[0] instanceof Number) && ! (data[0] instanceof String)) { + throw new PainterException("eq: wrong arguments"); + } + if (data[0] instanceof Number) { + if (! (data[1] instanceof Number)) { + throw new PainterException("eq: wrong arguments"); + } + double d0, d1; + d0 = ( (Number) data[0]).doubleValue(); + d1 = ( (Number) data[1]).doubleValue(); + if (d0 == d1) { + context.operands.push(new Boolean(true)); + } + else { + context.operands.push(new Boolean(false)); + } + } + else { + if (! (data[1] instanceof String)) { + throw new PainterException("eq: wrong arguments"); + } + String s0, s1; + s0 = (String) data[0]; + s1 = (String) data[1]; + if (s0.compareTo(s1) == 0) { + context.operands.push(new Boolean(true)); + } + else { + context.operands.push(new Boolean(false)); + } + } + } + }); + + // if + systemDict.put("if", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + PAToken patoken; + data = context.popOperands(2); + if (! (data[0] instanceof Boolean)) { + throw new PainterException("if: wrong arguments"); + } + if (! (data[1] instanceof PAToken)) { + throw new PainterException("if: wrong arguments"); + } + patoken = (PAToken) data[1]; + if (! (patoken.type == PAToken.PROCEDURE)) { + throw new PainterException("if: wrong arguments"); + } + if ( ( (Boolean) data[0]).booleanValue()) { + context.engine.process(patoken); + } + } + }); + + // ifelse + systemDict.put("ifelse", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + PAToken patoken1, patoken2; + data = context.popOperands(3); + if (! (data[0] instanceof Boolean)) { + throw new PainterException("ifelse: wrong arguments"); + } + if (! (data[1] instanceof PAToken)) { + throw new PainterException("ifelse: wrong arguments"); + } + if (! (data[2] instanceof PAToken)) { + throw new PainterException("ifelse: wrong arguments"); + } + patoken1 = (PAToken) data[1]; + patoken2 = (PAToken) data[2]; + if (! (patoken1.type == PAToken.PROCEDURE)) { + throw new PainterException("ifelse: wrong arguments"); + } + if (! (patoken2.type == PAToken.PROCEDURE)) { + throw new PainterException("ifelse: wrong arguments"); + } + if ( ( (Boolean) data[0]).booleanValue()) { + context.engine.process(patoken1); + } + else { + context.engine.process(patoken2); + } + } + }); + + // dict + systemDict.put("dict", new PACommand() { + public void execute(PAContext context) throws PainterException { + double data[]; + data = context.popNumberOperands(1); + context.operands.push(new HashMap( (int) data[0])); + } + }); + + // put + systemDict.put("put", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + PAToken patoken; + data = context.popOperands(3); + if ( (data[0] instanceof HashMap) && (data[1] instanceof PAToken)) { + patoken = (PAToken) data[1]; + if (! (patoken.type == PAToken.KEY)) { + throw new PainterException("put: wrong arguments"); + } + ( (HashMap) data[0]).put(patoken.value, data[2]); + } + else + if ( (data[0] instanceof ArrayList) && (data[1] instanceof Number)) { + ArrayList ar = (ArrayList) data[0]; + Number nr = (Number) data[1]; + ar.set(nr.intValue(), data[2]); + } + else + if ( (data[0] instanceof StringBuffer) && (data[1] instanceof Number) && + (data[2] instanceof Number)) { + StringBuffer text = (StringBuffer) data[0]; + Number nr = (Number) data[1]; + Number ch = (Number) data[2]; + text.setCharAt(nr.intValue(), (char) (ch.intValue())); + } + else { + throw new PainterException("put: wrong arguments"); + } + } + }); + + // get + systemDict.put("get", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + PAToken patoken; + data = context.popOperands(2); + if (! (data[0] instanceof HashMap) && ! (data[0] instanceof ArrayList)) { + throw new PainterException("get: wrong arguments"); + } + if (data[0] instanceof HashMap) { + if (! (data[1] instanceof PAToken)) { + throw new PainterException("get: wrong arguments"); + } + patoken = (PAToken) data[1]; + if (! (patoken.type == PAToken.KEY)) { + throw new PainterException("get: wrong arguments"); + } + context.operands.push( ( (HashMap) data[0]).get(patoken.value)); + } + else if (data[0] instanceof ArrayList) { + if (! (data[1] instanceof Number)) { + throw new PainterException("get: wrong arguments"); + } + context.operands.push( ( (ArrayList) data[0]).get( ( (Number) data[1]). + intValue())); + } + } + }); + // getinterval + systemDict.put("getinterval", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + PAToken patoken; + data = context.popOperands(3); + if (! (data[0] instanceof HashMap) && ! (data[0] instanceof ArrayList)) { + throw new PainterException("getinterval: wrong arguments"); + } + if (data[0] instanceof HashMap) { + if (! (data[1] instanceof PAToken)) { + throw new PainterException("getinterval: wrong arguments"); + } + patoken = (PAToken) data[1]; + if (! (patoken.type == PAToken.KEY)) { + throw new PainterException("getinterval: wrong arguments"); + } + if (! (data[2] instanceof Number)) { + throw new PainterException("getinterval: wrong arguments"); + } + HashMap target = new HashMap(); + context.operands.push( ( (HashMap) data[0]).get(patoken.value)); + } + else if (data[0] instanceof ArrayList) { + if (! (data[1] instanceof Number)) { + throw new PainterException("getinterval: wrong arguments"); + } + if (! (data[2] instanceof Number)) { + throw new PainterException("getinterval: wrong arguments"); + } + ArrayList source = ( (ArrayList) data[0]); + int from = ( (Number) data[1]).intValue(); + int to = from + ( (Number) data[2]).intValue(); + ArrayList target = new ArrayList(source.subList(from, to)); + context.operands.push(target); + } + } + }); + // load + systemDict.put("load", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + PAToken patoken; + data = context.popOperands(1); + if (! (data[0] instanceof PAToken)) { + throw new PainterException("load: wrong arguments"); + } + patoken = (PAToken) data[0]; + if (! (patoken.type == PAToken.KEY)) { + throw new PainterException("load: wrong arguments"); + } + context.operands.push(context.findIdentifier(patoken.value)); + } + }); + + // length + systemDict.put("length", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + PAToken patoken; + int size = 0; + data = context.popOperands(1); + if (data[0] instanceof PAToken) { + patoken = (PAToken) data[0]; + if (! (patoken.type == PAToken.KEY)) { + throw new PainterException("length: wrong arguments"); + } + size = ( (String) patoken.value).length(); + } + else if (data[0] instanceof HashMap) { + size = ( (HashMap) data[0]).size(); + } + else if (data[0] instanceof ArrayList) { + size = ( (ArrayList) data[0]).size(); + } + else if (data[0] instanceof String) { + size = ( (String) data[0]).length(); + } + else { + throw new PainterException("length: wrong arguments"); + } + + context.operands.push(new Integer(size)); + } + }); + + // begin + systemDict.put("begin", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + data = context.popOperands(1); + if (! (data[0] instanceof HashMap)) { + throw new PainterException("begin: wrong arguments"); + } + context.dictionaries.push(data[0]); + } + }); + + // end + systemDict.put("end", new PACommand() { + public void execute(PAContext context) throws PainterException { + try { + context.dictionaries.pop(); + } + catch (EmptyStackException e) { + throw new PainterException("Dictionary stack is empty"); + } + } + }); + + // undef + systemDict.put("undef", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + PAToken patoken; + data = context.popOperands(2); + if (! (data[0] instanceof HashMap)) { + throw new PainterException("undef: wrong arguments"); + } + if (! (data[1] instanceof PAToken)) { + throw new PainterException("undef: wrong arguments"); + } + patoken = (PAToken) data[1]; + if (! (patoken.type == PAToken.KEY)) { + throw new PainterException("undef: wrong arguments"); + } + // we don't do an actual undef because we don't care + } + }); + + // known + systemDict.put("known", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[], foundObject; + PAToken patoken; + data = context.popOperands(1); + if (! (data[0] instanceof PAToken)) { + throw new PainterException("known: wrong arguments"); + } + patoken = (PAToken) data[0]; + if (! (patoken.type == PAToken.KEY)) { + throw new PainterException("known: wrong arguments"); + } + foundObject = context.findIdentifier(patoken.value); + if (foundObject != null) { + context.operands.push(new Boolean(true)); + } + else { + context.operands.push(new Boolean(false)); + } + } + }); + + // where + systemDict.put("where", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[], foundObject; + PAToken patoken; + data = context.popOperands(1); + if (! (data[0] instanceof PAToken)) { + throw new PainterException("where: wrong arguments"); + } + patoken = (PAToken) data[0]; + if (! (patoken.type == PAToken.KEY)) { + throw new PainterException("where: wrong arguments"); + } + foundObject = context.findDictionary(patoken.value); + if (foundObject != null) { + context.operands.push(foundObject); + context.operands.push(new Boolean(true)); + } + else { + context.operands.push(new Boolean(false)); + } + } + }); + + // aload + systemDict.put("aload", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object[] data; + java.util.AbstractList list; + data = context.popOperands(1); + if (data[0] instanceof PAToken) { + data[0] = ( (PAToken) data[0]).value; + } + if (! (data[0] instanceof java.util.AbstractList)) { + throw new PainterException("aload: wrong arguments"); + } + + list = (java.util.AbstractList) data[0]; + Iterator iterator = list.iterator(); + while (iterator.hasNext()) { + context.operands.push(iterator.next()); + } + context.operands.push(data[0]); + } + }); + + // forall + systemDict.put("forall", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + ArrayList list; + PAToken patoken; + + data = context.popOperands(2); + if (! (data[0] instanceof ArrayList)) { + throw new PainterException("forall: wrong arguments"); + } + if (! (data[1] instanceof PAToken)) { + throw new PainterException("forall: wrong arguments"); + } + + patoken = (PAToken) data[1]; + if (! (patoken.type == PAToken.PROCEDURE)) { + throw new PainterException("forall: wrong arguments"); + } + + list = (ArrayList) data[0]; + Iterator iterator = list.iterator(); + while (iterator.hasNext()) { + context.operands.push(iterator.next()); + context.engine.process(patoken); + } + + } + }); + + // currentflat PENDING(uweh):placeholder for now + systemDict.put("currentflat", new PACommand() { + public void execute(PAContext context) throws PainterException { + PdfGraphics2D pdfg2d = (PdfGraphics2D) context.pencil.graphics; + PdfContentByte cb = pdfg2d.getContent(); + context.operands.push(new Double(1.0f)); + } + }); + + // setflat PENDING(uweh):placeholder for now + systemDict.put("setflat", new PACommand() { + public void execute(PAContext context) throws PainterException { + double[] data; + data = context.popNumberOperands(1); + PdfGraphics2D pdfg2d = (PdfGraphics2D) context.pencil.graphics; + PdfContentByte cb = pdfg2d.getContent(); + cb.setFlatness( ( (float) data[0])); + } + }); + + // round + systemDict.put("round", new PACommand() { + public void execute(PAContext context) throws PainterException { + double data[]; + data = context.popNumberOperands(1); + context.operands.push(new Long(Math.round(data[0]))); + } + }); + + // abs + systemDict.put("abs", new PACommand() { + public void execute(PAContext context) throws PainterException { + double data[]; + data = context.popNumberOperands(1); + context.operands.push(new Double(Math.abs(data[0]))); + } + }); + + // transform + systemDict.put("transform", new PACommand() { + public void execute(PAContext context) throws PainterException { + if (context.peekOperand() instanceof Number) { + double data[]; + double[] transformedData = new double[2]; + data = context.popNumberOperands(2); + AffineTransform at = context.pencil.graphics.getTransform(); + at.transform(data, 0, transformedData, 0, 1); + context.operands.push(new Double(transformedData[0])); + context.operands.push(new Double(transformedData[1])); + } + else { + Object data[]; + + data = context.popOperands(3); + if (! (data[0] instanceof Number)) { + throw new PainterException("transform: wrong arguments"); + } + if (! (data[1] instanceof Number)) { + throw new PainterException("transform: wrong arguments"); + } + if (! (data[2] instanceof ArrayList)) { + throw new PainterException("transform: wrong arguments"); + } + + ArrayList array = (ArrayList) data[2]; + + double[] entries = new double[6]; + + if (! (array.size() == 6)) { + throw new PainterException("transform: wrong arguments"); + } + + for (int i = 0; i < 6; i++) { + entries[i] = ( (Number) array.get(i)).doubleValue(); + } + + AffineTransform at = new AffineTransform(entries); + + double numberdata[] = new double[2]; + numberdata[0] = ( (Number) data[0]).doubleValue(); + numberdata[1] = ( (Number) data[1]).doubleValue(); + + double[] transformedData = new double[2]; + + at.transform(numberdata, 0, transformedData, 0, 1); + context.operands.push(new Double(transformedData[0])); + context.operands.push(new Double(transformedData[1])); + } + } + }); + + // itransform + systemDict.put("itransform", new PACommand() { + public void execute(PAContext context) throws PainterException { + if (context.peekOperand() instanceof Number) { + double data[]; + double[] transformedData = new double[2]; + data = context.popNumberOperands(2); + AffineTransform at = context.pencil.graphics.getTransform(); + try { + at.inverseTransform(data, 0, transformedData, 0, 1); + } + catch (NoninvertibleTransformException e) { + throw new PainterException(e.toString()); + } + context.operands.push(new Double(transformedData[0])); + context.operands.push(new Double(transformedData[1])); + } + else { + Object data[]; + + data = context.popOperands(3); + if (! (data[0] instanceof Number)) { + throw new PainterException("itransform: wrong arguments"); + } + if (! (data[1] instanceof Number)) { + throw new PainterException("itransform: wrong arguments"); + } + if (! (data[2] instanceof ArrayList)) { + throw new PainterException("itransform: wrong arguments"); + } + + ArrayList array = (ArrayList) data[2]; + + double[] entries = new double[6]; + + if (! (array.size() == 6)) { + throw new PainterException("itransform: wrong arguments"); + } + + for (int i = 0; i < 6; i++) { + entries[i] = ( (Number) array.get(i)).doubleValue(); + } + + AffineTransform at = new AffineTransform(entries); + + double numberdata[] = new double[2]; + numberdata[0] = ( (Number) data[0]).doubleValue(); + numberdata[1] = ( (Number) data[0]).doubleValue(); + + double[] transformedData = new double[2]; + + try { + at.inverseTransform(numberdata, 0, transformedData, 0, 1); + } + catch (NoninvertibleTransformException e) { + throw new PainterException(e.toString()); + } + context.operands.push(new Double(transformedData[0])); + context.operands.push(new Double(transformedData[1])); + } + } + }); + + // currentpoint + // PENDING(uweh): what about CTM, same thing when you construct path + // this is different than ps, might not work in a few instances + systemDict.put("currentpoint", new PACommand() { + public void execute(PAContext context) throws PainterException { + Point2D currentPoint = context.pencil.state.path.getCurrentPoint(); + context.operands.push(new Double(currentPoint.getX())); + context.operands.push(new Double(currentPoint.getY())); + } + }); + + // clippath + systemDict.put("clippath", new PACommand() { + public void execute(PAContext context) throws PainterException { + context.pencil.clippath(); + } + }); + + // matrix + systemDict.put("matrix", new PACommand() { + public void execute(PAContext context) throws PainterException { + ArrayList identityMatrix = new ArrayList(6); + + identityMatrix.add(new Double(1.0d)); + identityMatrix.add(new Double(0.0d)); + identityMatrix.add(new Double(0.0d)); + identityMatrix.add(new Double(1.0d)); + identityMatrix.add(new Double(0.0d)); + identityMatrix.add(new Double(0.0d)); + context.operands.push(identityMatrix); + } + }); + + // concatmatrix + systemDict.put("concatmatrix", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + data = context.popOperands(3); + if (! (data[0] instanceof ArrayList)) { + throw new PainterException("concatmatrix: wrong arguments"); + } + if (! (data[1] instanceof ArrayList)) { + throw new PainterException("concatmatrix: wrong arguments"); + } + if (! (data[2] instanceof ArrayList)) { + throw new PainterException("concatmatrix: wrong arguments"); + } + ArrayList arrayOne, arrayTwo, arrayThree; + AffineTransform atOne, atTwo; + + arrayOne = (ArrayList) data[0]; + arrayTwo = (ArrayList) data[1]; + arrayThree = (ArrayList) data[2]; + + double[] entries = new double[6]; + + if (! (arrayOne.size() == 6)) { + throw new PainterException("concatmatrix: wrong arguments"); + } + if (! (arrayTwo.size() == 6)) { + throw new PainterException("concatmatrix: wrong arguments"); + } + if (! (arrayThree.size() == 6)) { + throw new PainterException("concatmatrix: wrong arguments"); + } + + for (int i = 0; i < 6; i++) { + entries[i] = ( (Number) arrayOne.get(i)).doubleValue(); + } + atOne = new AffineTransform(entries); + for (int i = 0; i < 6; i++) { + entries[i] = ( (Number) arrayTwo.get(i)).doubleValue(); + } + atTwo = new AffineTransform(entries); + + atOne.concatenate(atTwo); + + atOne.getMatrix(entries); + for (int i = 0; i < 6; i++) { + arrayThree.set(i, new Double(entries[i])); + } + context.operands.push(arrayThree); + } + }); + + // pathbbox + systemDict.put("pathbbox", new PACommand() { + public void execute(PAContext context) throws PainterException { + Rectangle2D pathBounds = context.pencil.state.path.getBounds2D(); + + context.operands.push(new Double(pathBounds.getMinX())); + context.operands.push(new Double(pathBounds.getMinY())); + context.operands.push(new Double(pathBounds.getMaxX())); + context.operands.push(new Double(pathBounds.getMaxY())); + } + }); + + // initmatrix + systemDict.put("initmatrix", new PACommand() { + public void execute(PAContext context) throws PainterException { + PdfGraphics2D pdfg2d = (PdfGraphics2D) context.pencil.graphics; + PdfContentByte cb = pdfg2d.getContent(); +// cb.transform(Affine); + } + }); + // initclip + systemDict.put("initclip", new PACommand() { + public void execute(PAContext context) throws PainterException { + PdfGraphics2D pdfg2d = (PdfGraphics2D) context.pencil.graphics; + PdfContentByte cb = pdfg2d.getContent(); + context.pencil.clippath(); +// pdfg2d.setClip(context.); +// if(!PAContext.IgnoreUnknownCommands) +// throw new UnsupportedOperationException("initclip"); + } + }); + + // truncate + systemDict.put("truncate", new PACommand() { + public void execute(PAContext context) throws PainterException { + double data[]; + double truncated; + + data = context.popNumberOperands(1); + if (data[0] < 0) { + truncated = Math.ceil(data[0]); + } + else { + truncated = Math.floor(data[0]); + } + context.operands.push(new Double(truncated)); + } + }); + + // rand + systemDict.put("rand", new PACommand() { + public void execute(PAContext context) throws PainterException { + context.operands.push(new Integer(Math.abs(randomNumberGenerator. + nextInt( (1 << 31) - 1)))); + } + }); + + // srand + systemDict.put("srand", new PACommand() { + public void execute(PAContext context) throws PainterException { + double data[]; + + data = context.popNumberOperands(1); + randomNumberGenerator = new Random(Math.round(data[0])); + } + }); + // version + systemDict.put("version", new PACommand() { + public void execute(PAContext context) throws PainterException { + context.operands.push("2016"); + } + }); + // cvi + systemDict.put("cvi", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + + data = context.popOperands(1); + if (! (data[0] instanceof Number) && ! (data[0] instanceof String)) { + throw new PainterException("cvi: wrong arguments"); + } + if (data[0] instanceof Number) { + int d; + + d = ( (Number) data[0]).intValue(); + context.operands.push(new Integer(d)); + } + else { + String s; + s = (String) data[0]; + + context.operands.push(new Integer(s)); + } + } + }); + // cvr + systemDict.put("cvr", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + + data = context.popOperands(1); + if (! (data[0] instanceof Number) && ! (data[0] instanceof String)) { + throw new PainterException("cvr: wrong arguments"); + } + if (data[0] instanceof Number) { + int d; + + d = ( (Number) data[0]).intValue(); + context.operands.push(new Double(d)); + } + else { + String s; + s = (String) data[0]; + + context.operands.push(new Double(s)); + } + } + }); + // usertime + systemDict.put("usertime", new PACommand() { + public void execute(PAContext context) throws PainterException { + context.operands.push(new Long(System.currentTimeMillis())); + } + }); +// save + systemDict.put("save", new PACommand() { + public void execute(PAContext context) throws PainterException { + PdfGraphics2D pdfg2d = (PdfGraphics2D) context.pencil.graphics; + PdfContentByte cb = pdfg2d.getContent(); + cb.saveState(); + context.operands.push(new Long(0)); + } + }); +// restore + systemDict.put("restore", new PACommand() { + public void execute(PAContext context) throws PainterException { + PdfGraphics2D pdfg2d = (PdfGraphics2D) context.pencil.graphics; + PdfContentByte cb = pdfg2d.getContent(); + cb.restoreState(); + Object data[]; + data = context.popOperands(1); + } + }); +// clear + systemDict.put("clear", new PACommand() { + public void execute(PAContext context) throws PainterException { + context.operands.clear(); + } + }); + // readonly + systemDict.put("readonly", new PACommand() { + public void execute(PAContext context) throws PainterException { + } + }); + +// currentfile + systemDict.put("currentfile", new PACommand() { + public void execute(PAContext context) throws PainterException { + final JavaCharStream jcs=context.poorscript.jj_input_stream; + InputStream ins=new InputStream(){ + /** + * Reads the next byte of data from the input stream. + * + * @return the next byte of data, or -1 if the end of the stream is reached. + * @throws IOException if an I/O error occurs. + * @todo Implement this java.io.InputStream method + */ + public int read() throws IOException { + return jcs.readChar(); + } + + }; + context.operands.push(ins); + } + }); + // flushfile + systemDict.put("flushfile", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + data = context.popOperands(1); + if (! (data[0] instanceof InputStream)) { + throw new PainterException("flushfile: wrong arguments"); + } + + InputStream is = (InputStream) data[0]; + try { + while (is.read() != -1) { + } + } + catch (IOException ex) { + } + } + }); + + // closefile + systemDict.put("closefile", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + data = context.popOperands(1); + if (! (data[0] instanceof InputStream)) { + throw new PainterException("closefile: wrong arguments"); + } + + InputStream is = (InputStream) data[0]; + try { + is.close(); + } + catch (IOException ex) { + } + } + }); + + // string + systemDict.put("string", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + data = context.popOperands(1); + if (! (data[0] instanceof Number)) { + throw new PainterException("string: wrong arguments"); + } + int d; + d = ( (Number) data[0]).intValue(); + StringBuffer sb = new StringBuffer(d); + sb.setLength(d); + context.operands.push(sb); + } + }); + // null + systemDict.put("null", new PACommand() { + public void execute(PAContext context) throws PainterException { + context.operands.push(null); + } + }); + // currentscreen + systemDict.put("currentscreen", new PACommand() { + public void execute(PAContext context) throws PainterException { + if (!PAContext.IgnoreUnknownCommands) { + throw new UnsupportedOperationException("currentscreen"); + } + else { + context.operands.push(new Double(60)); + context.operands.push(new Double(0)); + context.operands.push(new Double(0)); + } + } + }); + // setscreen + systemDict.put("setscreen", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + data = context.popOperands(3); + +// if (!PAContext.IgnoreUnknownCommands) +// throw new UnsupportedOperationException("setscreen"); +// else { +// +// } + } + }); + + // flattenpath + systemDict.put("flattenpath", new PACommand() { + public void execute(PAContext context) throws PainterException { + + } + }); + // filter + systemDict.put("filter", new PACommand() { + public void execute(PAContext context) throws PainterException { + String filtername; + filtername = (String) ( (PAToken) context.popOperands(1)[0]).value; + Object obj; + while (! ( (obj = context.peekOperand()) instanceof InputStream)) { + Object param = context.popOperands(1); + } + + InputStream datasrc; + datasrc = (InputStream) (context.popOperands(1)[0]); + + InputStream dis; + if (filtername.equals("ASCIIHexDecode")) { + // dis = new ASCIIHexInputStream(datasrc); + final InputStream is=datasrc; + dis=new InputStream(){ + + /** + * Reads the next byte of data from the input stream. + * + * @return the next byte of data, or -1 if the end of the stream is reached. + * @throws IOException if an I/O error occurs. + * @todo Implement this java.io.InputStream method + */ + public int read() throws IOException { + int firstchar,secondchar; + for(;;){ + firstchar=is.read(); + if(firstchar==-1)return -1; + if(firstchar=='>')return -1; + if(firstchar=='\n')continue; + if(firstchar=='\r')continue; + break; + } + for(;;){ + secondchar=is.read(); + if(secondchar=='>')return -1; + if(secondchar==-1)return -1; + if(secondchar=='\n')continue; + if(secondchar=='\r')continue; + break; + } + int highbyte=0; + if(firstchar>=48&&firstchar<=57)highbyte=firstchar-48; + if(firstchar>=65&&firstchar<=70)highbyte=firstchar-55; + int lowbyte=0; + if(secondchar>=48&&secondchar<=57)lowbyte=secondchar-48; + if(secondchar>=65&&secondchar<=70)lowbyte=secondchar-55; + + return(highbyte*16+lowbyte); + } + }; + } +// else +// if (filtername.equals("DCTDecode")) { +// dis = new DCTInputStream(datasrc); +// } + else { + dis = datasrc; + } + + context.operands.push(dis); + } + }); + // clip + systemDict.put("clip", new PACommand() { + public void execute(PAContext context) throws PainterException { + context.pencil.clip(); + } + }); + // setcolorspace + systemDict.put("setcolorspace", new PACommand() { + public void execute(PAContext context) throws PainterException { + PdfGraphics2D pdfg2d = (PdfGraphics2D) context.pencil.graphics; + PdfContentByte cb = pdfg2d.getContent(); + Object data[]; + data = context.popOperands(1); + if (data[0] instanceof PAToken) { + String colorspace = ( (String) ( (PAToken) data[0]).value); + cb.setDefaultColorspace(PdfName.COLORSPACE, PdfName.DEVICERGB); + + } + } + }); + // image + systemDict.put("image", new PACommand() { + public void execute(PAContext context) throws PainterException { + PdfGraphics2D pdfg2d = (PdfGraphics2D) context.pencil.graphics; + PdfContentByte cb = pdfg2d.getContent(); + Object data[]; + data = context.popOperands(1); + if (data[0] instanceof Number) { + /** + * Level1 image + */ + int width = ( (Number) data[0]).intValue(); + data = context.popOperands(4); + int height = ( (Number) data[0]).intValue(); + int bits = ( (Number) data[1]).intValue(); + + }else if (data[0] instanceof PAToken) { + PAToken proc = (PAToken) data[0]; + + data = context.popOperands(4); + int width = ( (Number) data[0]).intValue(); + int height = ( (Number) data[1]).intValue(); + int bitspercomponent = ( (Number) data[2]).intValue(); + ArrayList ar = (ArrayList) data[3]; + System.out.println("I " + width + "*" + height + " " + + bitspercomponent + " " + ar); + +// context.engine.process(proc); + } + else if (data[0] instanceof HashMap){ + HashMap hsm = (HashMap) data[0]; + Iterator it = hsm.keySet().iterator(); + int width = 0, height = 0, bitspercomponent = 0; + int imagetype = 0; + InputStream datasrc = null; + Object decode = null; + Object imagematrix = null; + while (it.hasNext()) { + PAToken token = (PAToken) it.next(); + if (token.value.toString().equals("ImageType")) { + imagetype = ( (Number) hsm.get(token)).intValue(); + } + if (token.value.toString().equals("DataSource")) { + datasrc = (InputStream) hsm.get(token); + } + + if (token.value.toString().equals("BitsPerComponent")) { + bitspercomponent = ( (Number) hsm.get(token)).intValue(); + } + if (token.value.toString().equals("Width")) { + width = ( (Number) hsm.get(token)).intValue(); + } + if (token.value.toString().equals("Height")) { + height = ( (Number) hsm.get(token)).intValue(); + } + if (token.value.toString().equals("Decode")) { + decode = ( (Object) hsm.get(token)); + } + if (token.value.toString().equals("ImageMatrix")) { + imagematrix = ( (Object) hsm.get(token)); + } + } + + try { + byte[] barr = {}; + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + int aByte; + while ( (aByte = datasrc.read()) >= 0) { + bout.write(aByte); +// System.out.print((char)aByte); + } + System.out.println("I " + width + "*" + height + " " + + bitspercomponent + " " + imagetype + " " + + decode + " " + imagematrix + " " + datasrc); + barr = bout.toByteArray(); +// com.lowagie.text.Image img = new ImgRaw(width, height, 1, +// bitspercomponent, barr); + com.lowagie.text.Image img = new Jpeg(barr); + try { + cb.addImage(img,width,0,0,height,0,0); + } + catch (DocumentException ex1) { + ex1.printStackTrace(); + } + } + catch (IOException ex) { + ex.printStackTrace(); + } + catch (BadElementException ex) { + ex.printStackTrace(); + } + + } + } + }); + + // imagemask + systemDict.put("imagemask", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + data = context.popOperands(5); +// if (data[0] instanceof PAToken) { +// PAToken token = (PAToken) data[0]; +// context.engine.process(token); +// } + } + }); + + + // exec + systemDict.put("exec", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + data = context.popOperands(1); + if (data[0] instanceof PAToken) { + PAToken token = (PAToken) data[0]; + context.engine.process(token); + } + } + }); + // currentdict + systemDict.put("currentdict", new PACommand() { + public void execute(PAContext context) throws PainterException { + context.operands.push(context.dictionaries.peek()); + } + }); + +// cleardictstack + systemDict.put("cleardictstack", new PACommand() { + public void execute(PAContext context) throws PainterException { + context.dictionaries.clear(); + HashMap systemDict = context.constructSystemDict(); + context.dictionaries.push(systemDict); + HashMap globalDict = context.constructGlobalDict(); + context.dictionaries.push(globalDict); + HashMap userDict = context.constructUserDict(); + systemDict.put("userdict", userDict); + systemDict.put("globaldict", globalDict); + context.dictionaries.push(userDict); + } + }); + + // charpath + systemDict.put("charpath", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + + data = context.popOperands(2); + if (! (data[0] instanceof String)) { + throw new PainterException("charpath: wrong arguments"); + } + if (! (data[1] instanceof Boolean)) { + throw new PainterException("charpath: wrong arguments"); + } + + context.pencil.charpath( (String) data[0], + ( (Boolean) data[1]).booleanValue()); + } + }); + + // PENDING(uweh): we only support procedure right now and always push false on the stack + // stopped + systemDict.put("stopped", new PACommand() { + public void execute(PAContext context) throws PainterException { + Object data[]; + PAToken patoken; + data = context.popOperands(1); + if (! (data[0] instanceof PAToken)) { + throw new PainterException("stopped: wrong arguments"); + } + + patoken = (PAToken) data[0]; + if (! (patoken.type == PAToken.PROCEDURE)) { + throw new PainterException("stopped: wrong arguments"); + } + context.engine.process(patoken); + context.operands.push(new Boolean(false)); + } + }); + systemDict.put("systemdict", systemDict); + return systemDict; + } + + /** + *

Title:

+ * + *

Description:

+ * + *

Copyright: Copyright (c) 2006

+ * + *

Company:

+ * @author not attributable + * @version 1.0 + */ + private class NamedInputStream extends InputStream{ + public String filename; + InputStream in; + NamedInputStream(InputStream in,String filename) { + super(); + this.filename=filename; + this.in=in; + } + public int read() throws IOException { + return in.read(); + } + } +} diff --git a/src/main/java/com/lowagie/text/pdf/codec/postscript/PAEngine.java b/src/main/java/com/lowagie/text/pdf/codec/postscript/PAEngine.java new file mode 100644 index 0000000..e905402 --- /dev/null +++ b/src/main/java/com/lowagie/text/pdf/codec/postscript/PAEngine.java @@ -0,0 +1,155 @@ +/* + * Copyright 1998 by Sun Microsystems, Inc., + * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A. + * All rights reserved. + * + * This software is the confidential and proprietary information + * of Sun Microsystems, Inc. ("Confidential Information"). You + * shall not disclose such Confidential Information and shall use + * it only in accordance with the terms of the license agreement + * you entered into with Sun. + */ + +package com.lowagie.text.pdf.codec.postscript; + +import java.util.*; + + +public class PAEngine extends Object { + + static public final int MODE_STACK = 0; + static public final int MODE_PROCEDURE = 1; + static public final int MODE_ARRAY = 2; + + protected PAContext context; + protected int mode; + protected Stack procedure; + protected int innerProcedures; + + public PAEngine(PAContext context){ + super(); + this.context = context; + this.mode = PAEngine.MODE_STACK; + } + + public void startProcedure() throws PainterException { + this.procedure = new Stack(); + this.mode = PAEngine.MODE_PROCEDURE; + this.innerProcedures = 0; + } + + public void endProcedure() throws PainterException { + this.context.operands.push(new PAToken(this.procedure, PAToken.PROCEDURE)); + this.mode = PAEngine.MODE_STACK; + } + + public void bindProcedure(PAToken patoken){ + Stack oldStack = (Stack) patoken.value; + Stack newStack = new Stack(); + int i,n; + n = oldStack.size(); + for(i = 0; i < n; i++){ + Object token = oldStack.elementAt(i); + if((token instanceof PAToken) && ((PAToken) token).type == PAToken.IDENTIFIER){ + Object foundToken = this.context.findIdentifier(((PAToken) token).value); + if(foundToken == null){ + newStack.push(token); + } else { + newStack.push(foundToken); + } + } else { + newStack.push(token); + } + } + patoken.value = newStack; + } + + public void process(Object token) throws PainterException { + if(token == null){ + throw new IllegalStateException("Null token encountered; last unknown identifier was " + this.context.getLastUnknownIdentifier()+" at line "+this.context.poorscript.token.beginLine); + } + if(PAContext.DebugExecution){ + System.out.print("==>" + token.toString()); +// System.out.flush(); + } + if(token instanceof PAToken && ((PAToken) token).type == PAToken.IMMEDIATE){ + Object foundValue = this.context.findIdentifier(((PAToken) token).value); + this.process(foundValue); + return; + } + if(this.mode == MODE_STACK){ + if(token instanceof PACommand){ + ((PACommand) token).execute(this.context); + } else if(token instanceof PAToken){ + PAToken patoken = (PAToken) token; + + switch(patoken.type){ + case PAToken.IDENTIFIER: + this.process(this.context.findIdentifier(patoken.value)); + break; + case PAToken.KEY: + case PAToken.MARK: + case PAToken.START_ARRAY: + this.context.operands.push(token); + break; + case PAToken.PROCEDURE: + Enumeration enumx = ((Vector) patoken.value).elements(); + while(enumx.hasMoreElements()){ + this.process(enumx.nextElement()); + } + break; + case PAToken.START_PROCEDURE: + this.startProcedure(); + break; + case PAToken.END_ARRAY: + this.context.collectArray(); + break; + case PAToken.START_DICT: + this.context.operands.push(token); + break; + case PAToken.END_DICT: + this.context.collectDict(); + break; + default: + throw new IllegalStateException("Unknown token encountered" + token); + } + } else { + this.context.operands.push(token); + } + } else if(this.mode == MODE_PROCEDURE){ + if(token instanceof PAToken){ + PAToken patoken = (PAToken) token; + + switch(patoken.type){ + case PAToken.START_PROCEDURE: + this.innerProcedures++; + this.procedure.push(token); + break; + case PAToken.END_PROCEDURE: + if(this.innerProcedures > 0){ + this.innerProcedures--; + this.procedure.push(token); + } else { + this.endProcedure(); + } + break; + default: + this.procedure.push(token); + } + } else { + this.procedure.push(token); + } + } + } + + public String litMode(){ + switch(this.mode){ + case MODE_ARRAY: return "Array"; + case MODE_PROCEDURE: return "Proc"+innerProcedures; + case MODE_STACK: return "Stack"; + default: return "Unknown"; + } + } + +} + diff --git a/src/main/java/com/lowagie/text/pdf/codec/postscript/PAParser.java b/src/main/java/com/lowagie/text/pdf/codec/postscript/PAParser.java new file mode 100644 index 0000000..3c2c64a --- /dev/null +++ b/src/main/java/com/lowagie/text/pdf/codec/postscript/PAParser.java @@ -0,0 +1,351 @@ +/* Generated By:JavaCC: Do not edit this line. PAParser.java */ +package com.lowagie.text.pdf.codec.postscript; + +import java.lang.*; +import java.lang.reflect.*; +import java.util.*; +import java.awt.*; +import java.awt.geom.*; +import java.awt.color.*; +import java.awt.font.*; +import java.io.*; +import java.net.URL; + +public class PAParser extends Object implements PAParserConstants { + + void error_skipto(int kind) throws ParseException { +ParseException e=generateParseException(); +Token t; +String dump=""; +do{ +if(getToken(1).kind==kind)break; +t=getNextToken(); +dump+=t.image; +}while(t.kind!=kind); +System.out.println("Ignoriere >"+dump+"<"); + } + + String ExceptionString(String hint,JavaCharStream jj_input_stream,PAContext context,Token t,Exception e) throws ParseException { + return "\nparser "+hint+" ["+jj_input_stream.bufpos+"]"+context.engine.litMode()+":\""+t.image+"\" in line "+t.beginLine+" column "+t.beginColumn+"\n"+e.toString(); + } + + final public void parse(PAContext context) throws ParseException { + Token x = null; + try { + label_1: + while (true) { + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case INTEGER_LITERAL: + case FLOATING_POINT_LITERAL: + case STRING_LITERAL: + case IDENTIFIER: + case KEY_IDENTIFIER: + case IMMEDIATE_IDENTIFIER: + case LBRACE: + case RBRACE: + case LBRACKET: + case RBRACKET: + case LDICT: + case RDICT: + case Instring: + ; + break; + default: + jj_la1[0] = jj_gen; + break label_1; + } + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case INTEGER_LITERAL: + case FLOATING_POINT_LITERAL: + case STRING_LITERAL: + case IDENTIFIER: + case KEY_IDENTIFIER: + case IMMEDIATE_IDENTIFIER: + case Instring: + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case INTEGER_LITERAL: + x = jj_consume_token(INTEGER_LITERAL); + try { + {if(PAContext.DebugExecution){System.out.print("\nparser ["+jj_input_stream.getBeginLine()+","+jj_input_stream.getBeginColumn()+"]"+context.engine.litMode()+":\""+x.image+"\"");System.out.flush();System.err.flush();}} + context.engine.process(new Integer(x.image)); + } catch(NumberFormatException e) { + {if (true) throw new ParseException(ExceptionString("int_literal",jj_input_stream,context,token,e));} + } catch(PainterException e) { + {if (true) throw new ParseException(ExceptionString("int_literal",jj_input_stream,context,token,e));} + } + break; + case FLOATING_POINT_LITERAL: + x = jj_consume_token(FLOATING_POINT_LITERAL); + try { + {if(PAContext.DebugExecution){System.out.print("\nparser ["+jj_input_stream.getBeginLine()+","+jj_input_stream.getBeginColumn()+"]"+context.engine.litMode()+":\""+x.image+"\"");System.out.flush();System.err.flush();}} + context.engine.process(new Double(x.image)); + } catch(NumberFormatException e) { + {if (true) throw new ParseException(ExceptionString("float_literal",jj_input_stream,context,token,e));} + } catch(PainterException e) { + {if (true) throw new ParseException(ExceptionString("float_literal",jj_input_stream,context,token,e));} + } + break; + case Instring: + jj_consume_token(Instring); + x = jj_consume_token(HEX_STRING_LITERAL); + try { + {if(PAContext.DebugExecution){System.out.print("\nparser ["+jj_input_stream.getBeginLine()+","+jj_input_stream.getBeginColumn()+"]"+context.engine.litMode()+":\""+x.image+"\"");System.out.flush();System.err.flush();}} + context.engine.process((x.image.substring(1, x.image.length() -1))); + } catch(PainterException e) { + {if (true) throw new ParseException(ExceptionString("hex_string_literal",jj_input_stream,context,token,e));} + } + break; + case STRING_LITERAL: + x = jj_consume_token(STRING_LITERAL); + try { + {if(PAContext.DebugExecution){System.out.print("\nparser ["+jj_input_stream.getBeginLine()+","+jj_input_stream.getBeginColumn()+"]"+context.engine.litMode()+":\""+x.image+"\"");System.out.flush();System.err.flush();}} + context.engine.process(x.image.substring(1, x.image.length() -1)); + } catch(PainterException e) { + {if (true) throw new ParseException(ExceptionString("string_literal",jj_input_stream,context,token,e));} + } + break; + case IDENTIFIER: + x = jj_consume_token(IDENTIFIER); + try { + {if(PAContext.DebugExecution){System.out.print("\nparser ["+jj_input_stream.getBeginLine()+","+jj_input_stream.getBeginColumn()+"]"+context.engine.litMode()+":\""+x.image+"\"");System.out.flush();System.err.flush();}} + context.engine.process(new PAToken(x.image, PAToken.IDENTIFIER)); + } catch(PainterException e) { + {if (true) throw new ParseException(ExceptionString("identifier",jj_input_stream,context,token,e));} + } + break; + case KEY_IDENTIFIER: + x = jj_consume_token(KEY_IDENTIFIER); + try { + {if(PAContext.DebugExecution){System.out.print("\nparser ["+jj_input_stream.getBeginLine()+","+jj_input_stream.getBeginColumn()+"]"+context.engine.litMode()+":\""+x.image+"\"");System.out.flush();System.err.flush();}} + context.engine.process(new PAToken(x.image.substring(1, x.image.length()), PAToken.KEY)); + } catch(PainterException e) { + {if (true) throw new ParseException(ExceptionString("key_identifier",jj_input_stream,context,token,e));} + } + break; + case IMMEDIATE_IDENTIFIER: + x = jj_consume_token(IMMEDIATE_IDENTIFIER); + try { + {if(PAContext.DebugExecution){System.out.print("\nparser ["+jj_input_stream.getBeginLine()+","+jj_input_stream.getBeginColumn()+"]"+context.engine.litMode()+":\""+x.image+"\"");System.out.flush();System.err.flush();}} + context.engine.process(new PAToken(x.image.substring(2, x.image.length()), PAToken.IMMEDIATE)); + } catch(PainterException e) { + {if (true) throw new ParseException(ExceptionString("immediate_identifier",jj_input_stream,context,token,e));} + } + break; + default: + jj_la1[1] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + break; + case LBRACE: + jj_consume_token(LBRACE); + try { + {if(PAContext.DebugExecution){System.out.print("\nparser ["+jj_input_stream.getBeginLine()+","+jj_input_stream.getBeginColumn()+"]"+context.engine.litMode()+":\""+token.image+"\"");System.out.flush();System.err.flush();}} + context.engine.process(new PAToken(null, PAToken.START_PROCEDURE)); + } catch(PainterException e) { + {if (true) throw new ParseException(ExceptionString("lbrace",jj_input_stream,context,token,e));} + } + break; + case RBRACE: + jj_consume_token(RBRACE); + try { + {if(PAContext.DebugExecution){System.out.print("\nparser ["+jj_input_stream.getBeginLine()+","+jj_input_stream.getBeginColumn()+"]"+context.engine.litMode()+":\""+token.image+"\"");System.out.flush();System.err.flush();}} + context.engine.process(new PAToken(null, PAToken.END_PROCEDURE)); + } catch(PainterException e) { + {if (true) throw new ParseException(ExceptionString("rbrace",jj_input_stream,context,token,e));} + } + break; + case LBRACKET: + jj_consume_token(LBRACKET); + try { + {if(PAContext.DebugExecution){System.out.print("\nparser ["+jj_input_stream.getBeginLine()+","+jj_input_stream.getBeginColumn()+"]"+context.engine.litMode()+":\""+token.image+"\"");System.out.flush();System.err.flush();}} + context.engine.process(new PAToken(null, PAToken.START_ARRAY)); + } catch(PainterException e) { + {if (true) throw new ParseException(ExceptionString("lbracket",jj_input_stream,context,token,e));} + } + break; + case RBRACKET: + jj_consume_token(RBRACKET); + try { + {if(PAContext.DebugExecution){System.out.print("\nparser ["+jj_input_stream.getBeginLine()+","+jj_input_stream.getBeginColumn()+"]"+context.engine.litMode()+":\""+token.image+"\"");System.out.flush();System.err.flush();}} + context.engine.process(new PAToken(null, PAToken.END_ARRAY)); + } catch(PainterException e) { + {if (true) throw new ParseException(ExceptionString("rbracket",jj_input_stream,context,token,e));} + } + break; + case LDICT: + jj_consume_token(LDICT); + try { + {if(PAContext.DebugExecution){System.out.print("\nparser ["+jj_input_stream.getBeginLine()+","+jj_input_stream.getBeginColumn()+"]"+context.engine.litMode()+":\""+token.image+"\"");System.out.flush();System.err.flush();}} + context.engine.process(new PAToken(null, PAToken.START_DICT)); + } catch(PainterException e) { + {if (true) throw new ParseException(ExceptionString("ldict",jj_input_stream,context,token,e));} + } + break; + case RDICT: + jj_consume_token(RDICT); + try { + {if(PAContext.DebugExecution){System.out.print("\nparser ["+jj_input_stream.getBeginLine()+","+jj_input_stream.getBeginColumn()+"]"+context.engine.litMode()+":\""+token.image+"\"");System.out.flush();System.err.flush();}} + context.engine.process(new PAToken(null, PAToken.END_DICT)); + } catch(PainterException e) { + {if (true) throw new ParseException(ExceptionString("rdict",jj_input_stream,context,token,e));} + } + break; + default: + jj_la1[2] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + } + } catch (ParseException e) { + System.out.flush();System.err.flush(); + //System.out.println("Fehlerhaftes Element in Spalte "+e.currentToken.beginColumn+" in Eingabedatei in Zeile="+e.currentToken.next.beginLine+" in Zeichen Nr. "+e.currentToken.next.beginColumn+". >"+e.currentToken.next.image+"< wurde hier nicht erwartet."); + //System.err.println("Fehler:"+e); + e.printStackTrace(); + error_skipto(WHITESPACE); + System.exit(0); + } + } + + public PAParserTokenManager token_source; + JavaCharStream jj_input_stream; + public Token token, jj_nt; + private int jj_ntk; + private int jj_gen; + final private int[] jj_la1 = new int[3]; + final private int[] jj_la1_0 = {0x13f3d20,0x1003d20,0x13f3d20,}; + + public PAParser(java.io.InputStream stream) { + jj_input_stream = new JavaCharStream(stream, 1, 1); + token_source = new PAParserTokenManager(jj_input_stream); + token = new Token(); + jj_ntk = -1; + jj_gen = 0; + for (int i = 0; i < 3; i++) jj_la1[i] = -1; + } + + public void ReInit(java.io.InputStream stream) { + jj_input_stream.ReInit(stream, 1, 1); + token_source.ReInit(jj_input_stream); + token = new Token(); + jj_ntk = -1; + jj_gen = 0; + for (int i = 0; i < 3; i++) jj_la1[i] = -1; + } + + public PAParser(java.io.Reader stream) { + jj_input_stream = new JavaCharStream(stream, 1, 1); + token_source = new PAParserTokenManager(jj_input_stream); + token = new Token(); + jj_ntk = -1; + jj_gen = 0; + for (int i = 0; i < 3; i++) jj_la1[i] = -1; + } + + public void ReInit(java.io.Reader stream) { + jj_input_stream.ReInit(stream, 1, 1); + token_source.ReInit(jj_input_stream); + token = new Token(); + jj_ntk = -1; + jj_gen = 0; + for (int i = 0; i < 3; i++) jj_la1[i] = -1; + } + + public PAParser(PAParserTokenManager tm) { + token_source = tm; + token = new Token(); + jj_ntk = -1; + jj_gen = 0; + for (int i = 0; i < 3; i++) jj_la1[i] = -1; + } + + public void ReInit(PAParserTokenManager tm) { + token_source = tm; + token = new Token(); + jj_ntk = -1; + jj_gen = 0; + for (int i = 0; i < 3; i++) jj_la1[i] = -1; + } + + final private Token jj_consume_token(int kind) throws ParseException { + Token oldToken; + if ((oldToken = token).next != null) token = token.next; + else token = token.next = token_source.getNextToken(); + jj_ntk = -1; + if (token.kind == kind) { + jj_gen++; + return token; + } + token = oldToken; + jj_kind = kind; + throw generateParseException(); + } + + final public Token getNextToken() { + if (token.next != null) token = token.next; + else token = token.next = token_source.getNextToken(); + jj_ntk = -1; + jj_gen++; + return token; + } + + final public Token getToken(int index) { + Token t = token; + for (int i = 0; i < index; i++) { + if (t.next != null) t = t.next; + else t = t.next = token_source.getNextToken(); + } + return t; + } + + final private int jj_ntk() { + if ((jj_nt=token.next) == null) + return (jj_ntk = (token.next=token_source.getNextToken()).kind); + else + return (jj_ntk = jj_nt.kind); + } + + private java.util.Vector jj_expentries = new java.util.Vector(); + private int[] jj_expentry; + private int jj_kind = -1; + + final public ParseException generateParseException() { + jj_expentries.removeAllElements(); + boolean[] la1tokens = new boolean[25]; + for (int i = 0; i < 25; i++) { + la1tokens[i] = false; + } + if (jj_kind >= 0) { + la1tokens[jj_kind] = true; + jj_kind = -1; + } + for (int i = 0; i < 3; i++) { + if (jj_la1[i] == jj_gen) { + for (int j = 0; j < 32; j++) { + if ((jj_la1_0[i] & (1<", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "\"{\"", + "\"}\"", + "\"[\"", + "\"]\"", + "\"<<\"", + "\">>\"", + "", + "\">\"", + "\"<\"", + }; + +} diff --git a/src/main/java/com/lowagie/text/pdf/codec/postscript/PAParserTokenManager.java b/src/main/java/com/lowagie/text/pdf/codec/postscript/PAParserTokenManager.java new file mode 100644 index 0000000..9b908ba --- /dev/null +++ b/src/main/java/com/lowagie/text/pdf/codec/postscript/PAParserTokenManager.java @@ -0,0 +1,1011 @@ +/* Generated By:JavaCC: Do not edit this line. PAParserTokenManager.java */ +package com.lowagie.text.pdf.codec.postscript; +import java.lang.*; +import java.lang.reflect.*; +import java.util.*; +import java.awt.*; +import java.awt.geom.*; +import java.awt.color.*; +import java.awt.font.*; +import java.io.*; +import java.net.URL; + +public class PAParserTokenManager implements PAParserConstants +{ + public java.io.PrintStream debugStream = System.out; + public void setDebugStream(java.io.PrintStream ds) { debugStream = ds; } +private final int jjStopStringLiteralDfa_0(int pos, long active0) +{ + switch (pos) + { + default : + return -1; + } +} +private final int jjStartNfa_0(int pos, long active0) +{ + return jjMoveNfa_0(jjStopStringLiteralDfa_0(pos, active0), pos + 1); +} +private final int jjStopAtPos(int pos, int kind) +{ + jjmatchedKind = kind; + jjmatchedPos = pos; + return pos + 1; +} +private final int jjStartNfaWithStates_0(int pos, int kind, int state) +{ + jjmatchedKind = kind; + jjmatchedPos = pos; + try { curChar = input_stream.readChar(); } + catch(java.io.IOException e) { return pos + 1; } + return jjMoveNfa_0(state, pos + 1); +} +private final int jjMoveStringLiteralDfa0_0() +{ + switch(curChar) + { + case 60: + jjmatchedKind = 24; + return jjMoveStringLiteralDfa1_0(0x100000L); + case 62: + return jjMoveStringLiteralDfa1_0(0x200000L); + case 91: + return jjStopAtPos(0, 18); + case 93: + return jjStopAtPos(0, 19); + case 123: + return jjStopAtPos(0, 16); + case 125: + return jjStopAtPos(0, 17); + default : + return jjMoveNfa_0(0, 0); + } +} +private final int jjMoveStringLiteralDfa1_0(long active0) +{ + try { curChar = input_stream.readChar(); } + catch(java.io.IOException e) { + jjStopStringLiteralDfa_0(0, active0); + return 1; + } + switch(curChar) + { + case 60: + if ((active0 & 0x100000L) != 0L) + return jjStopAtPos(1, 20); + break; + case 62: + if ((active0 & 0x200000L) != 0L) + return jjStopAtPos(1, 21); + break; + default : + break; + } + return jjStartNfa_0(0, active0); +} +private final void jjCheckNAdd(int state) +{ + if (jjrounds[state] != jjround) + { + jjstateSet[jjnewStateCnt++] = state; + jjrounds[state] = jjround; + } +} +private final void jjAddStates(int start, int end) +{ + do { + jjstateSet[jjnewStateCnt++] = jjnextStates[start]; + } while (start++ != end); +} +private final void jjCheckNAddTwoStates(int state1, int state2) +{ + jjCheckNAdd(state1); + jjCheckNAdd(state2); +} +private final void jjCheckNAddStates(int start, int end) +{ + do { + jjCheckNAdd(jjnextStates[start]); + } while (start++ != end); +} +private final void jjCheckNAddStates(int start) +{ + jjCheckNAdd(jjnextStates[start]); + jjCheckNAdd(jjnextStates[start + 1]); +} +static final long[] jjbitVec0 = { + 0xfffffffffffffffeL, 0xffffffffffffffffL, 0xffffffffffffffffL, 0xffffffffffffffffL +}; +static final long[] jjbitVec2 = { + 0x0L, 0x0L, 0xffffffffffffffffL, 0xffffffffffffffffL +}; +static final long[] jjbitVec3 = { + 0x1ff00000fffffffeL, 0xffffffffffffc000L, 0xffffffffL, 0x600000000000000L +}; +static final long[] jjbitVec4 = { + 0x0L, 0x0L, 0x0L, 0xff7fffffff7fffffL +}; +static final long[] jjbitVec5 = { + 0x0L, 0xffffffffffffffffL, 0xffffffffffffffffL, 0xffffffffffffffffL +}; +static final long[] jjbitVec6 = { + 0xffffffffffffffffL, 0xffffffffffffffffL, 0xffffL, 0x0L +}; +static final long[] jjbitVec7 = { + 0xffffffffffffffffL, 0xffffffffffffffffL, 0x0L, 0x0L +}; +static final long[] jjbitVec8 = { + 0x3fffffffffffL, 0x0L, 0x0L, 0x0L +}; +private final int jjMoveNfa_0(int startState, int curPos) +{ + int[] nextStates; + int startsAt = 0; + jjnewStateCnt = 74; + int i = 1; + jjstateSet[0] = startState; + int j, kind = 0x7fffffff; + for (;;) + { + if (++jjround == 0x7fffffff) + ReInitRounds(); + if (curChar < 64) + { + long l = 1L << curChar; + MatchLoop: do + { + switch(jjstateSet[--i]) + { + case 0: + if ((0x3ff000000000000L & l) != 0L) + { + if (kind > 5) + kind = 5; + jjCheckNAddStates(0, 8); + } + else if ((0x100003610L & l) != 0L) + { + if (kind > 1) + kind = 1; + } + else if ((0x8000281000000000L & l) != 0L) + { + if (kind > 11) + kind = 11; + jjCheckNAdd(21); + } + else if (curChar == 37) + jjCheckNAddStates(9, 14); + else if (curChar == 47) + jjstateSet[jjnewStateCnt++] = 26; + else if (curChar == 40) + jjCheckNAddStates(15, 17); + else if (curChar == 46) + jjCheckNAdd(6); + if (curChar == 45) + jjCheckNAddStates(18, 23); + else if (curChar == 47) + jjCheckNAddTwoStates(23, 24); + else if (curChar == 48) + jjstateSet[jjnewStateCnt++] = 2; + break; + case 1: + if (curChar == 48) + jjstateSet[jjnewStateCnt++] = 2; + break; + case 3: + if ((0x3ff000000000000L & l) == 0L) + break; + if (kind > 5) + kind = 5; + jjCheckNAddTwoStates(3, 4); + break; + case 5: + if (curChar == 46) + jjCheckNAdd(6); + break; + case 6: + if ((0x3ff000000000000L & l) == 0L) + break; + if (kind > 8) + kind = 8; + jjCheckNAddStates(24, 26); + break; + case 8: + if ((0x280000000000L & l) != 0L) + jjCheckNAdd(9); + break; + case 9: + if ((0x3ff000000000000L & l) == 0L) + break; + if (kind > 8) + kind = 8; + jjCheckNAddTwoStates(9, 10); + break; + case 11: + if (curChar == 40) + jjCheckNAddStates(15, 17); + break; + case 12: + if ((0xfffffdffffffffffL & l) != 0L) + jjCheckNAddStates(15, 17); + break; + case 14: + if ((0x38000000400L & l) != 0L) + jjCheckNAddStates(15, 17); + break; + case 15: + if (curChar == 41 && kind > 10) + kind = 10; + break; + case 16: + if ((0xff000000000000L & l) != 0L) + jjCheckNAddStates(27, 30); + break; + case 17: + if ((0xff000000000000L & l) != 0L) + jjCheckNAddStates(15, 17); + break; + case 18: + if ((0xf000000000000L & l) != 0L) + jjstateSet[jjnewStateCnt++] = 19; + break; + case 19: + if ((0xff000000000000L & l) != 0L) + jjCheckNAdd(17); + break; + case 20: + if ((0x8000281000000000L & l) == 0L) + break; + if (kind > 11) + kind = 11; + jjCheckNAdd(21); + break; + case 21: + if ((0x83ff681000000000L & l) == 0L) + break; + if (kind > 11) + kind = 11; + jjCheckNAdd(21); + break; + case 22: + if (curChar == 47) + jjCheckNAddTwoStates(23, 24); + break; + case 23: + if ((0x400800000000L & l) != 0L) + jjCheckNAdd(24); + break; + case 24: + if ((0x8000281000000000L & l) == 0L) + break; + if (kind > 12) + kind = 12; + jjCheckNAdd(25); + break; + case 25: + if ((0x83ff681000000000L & l) == 0L) + break; + if (kind > 12) + kind = 12; + jjCheckNAdd(25); + break; + case 26: + if (curChar == 47) + jjstateSet[jjnewStateCnt++] = 27; + break; + case 27: + if ((0x8000281000000000L & l) == 0L) + break; + if (kind > 13) + kind = 13; + jjCheckNAdd(28); + break; + case 28: + if ((0x83ff681000000000L & l) == 0L) + break; + if (kind > 13) + kind = 13; + jjCheckNAdd(28); + break; + case 29: + if (curChar == 47) + jjstateSet[jjnewStateCnt++] = 26; + break; + case 30: + if (curChar == 37) + jjCheckNAddStates(9, 14); + break; + case 31: + if ((0xfffffffffffffbffL & l) != 0L) + jjCheckNAddTwoStates(31, 32); + break; + case 32: + if (curChar == 10 && kind > 2) + kind = 2; + break; + case 33: + if ((0xffffffffffffdfffL & l) != 0L) + jjCheckNAddTwoStates(33, 34); + break; + case 34: + if (curChar == 13 && kind > 3) + kind = 3; + break; + case 35: + if ((0xffffffffffffdfffL & l) != 0L) + jjCheckNAddTwoStates(35, 37); + break; + case 36: + if (curChar == 10 && kind > 4) + kind = 4; + break; + case 37: + if (curChar == 13) + jjstateSet[jjnewStateCnt++] = 36; + break; + case 38: + if (curChar == 45) + jjCheckNAddStates(18, 23); + break; + case 39: + if ((0x3ff000000000000L & l) == 0L) + break; + if (kind > 5) + kind = 5; + jjCheckNAddTwoStates(39, 4); + break; + case 40: + if ((0x3ff000000000000L & l) != 0L) + jjCheckNAddTwoStates(40, 41); + break; + case 41: + if (curChar != 46) + break; + if (kind > 8) + kind = 8; + jjCheckNAddStates(31, 33); + break; + case 42: + if ((0x3ff000000000000L & l) == 0L) + break; + if (kind > 8) + kind = 8; + jjCheckNAddStates(31, 33); + break; + case 44: + if ((0x280000000000L & l) != 0L) + jjCheckNAdd(45); + break; + case 45: + if ((0x3ff000000000000L & l) == 0L) + break; + if (kind > 8) + kind = 8; + jjCheckNAddTwoStates(45, 10); + break; + case 46: + if (curChar == 46) + jjCheckNAdd(47); + break; + case 47: + if ((0x3ff000000000000L & l) == 0L) + break; + if (kind > 8) + kind = 8; + jjCheckNAddStates(34, 36); + break; + case 49: + if ((0x280000000000L & l) != 0L) + jjCheckNAdd(50); + break; + case 50: + if ((0x3ff000000000000L & l) == 0L) + break; + if (kind > 8) + kind = 8; + jjCheckNAddTwoStates(50, 10); + break; + case 51: + if ((0x3ff000000000000L & l) != 0L) + jjCheckNAddTwoStates(51, 52); + break; + case 53: + if ((0x280000000000L & l) != 0L) + jjCheckNAdd(54); + break; + case 54: + if ((0x3ff000000000000L & l) == 0L) + break; + if (kind > 8) + kind = 8; + jjCheckNAddTwoStates(54, 10); + break; + case 55: + if ((0x3ff000000000000L & l) != 0L) + jjCheckNAddStates(37, 39); + break; + case 57: + if ((0x280000000000L & l) != 0L) + jjCheckNAdd(58); + break; + case 58: + if ((0x3ff000000000000L & l) != 0L) + jjCheckNAddTwoStates(58, 10); + break; + case 59: + if ((0x3ff000000000000L & l) == 0L) + break; + if (kind > 5) + kind = 5; + jjCheckNAddStates(0, 8); + break; + case 60: + if ((0x3ff000000000000L & l) != 0L) + jjCheckNAddTwoStates(60, 61); + break; + case 61: + if (curChar != 46) + break; + if (kind > 8) + kind = 8; + jjCheckNAddStates(40, 42); + break; + case 62: + if ((0x3ff000000000000L & l) == 0L) + break; + if (kind > 8) + kind = 8; + jjCheckNAddStates(40, 42); + break; + case 64: + if ((0x280000000000L & l) != 0L) + jjCheckNAdd(65); + break; + case 65: + if ((0x3ff000000000000L & l) == 0L) + break; + if (kind > 8) + kind = 8; + jjCheckNAddTwoStates(65, 10); + break; + case 66: + if ((0x3ff000000000000L & l) != 0L) + jjCheckNAddTwoStates(66, 67); + break; + case 68: + if ((0x280000000000L & l) != 0L) + jjCheckNAdd(69); + break; + case 69: + if ((0x3ff000000000000L & l) == 0L) + break; + if (kind > 8) + kind = 8; + jjCheckNAddTwoStates(69, 10); + break; + case 70: + if ((0x3ff000000000000L & l) != 0L) + jjCheckNAddStates(43, 45); + break; + case 72: + if ((0x280000000000L & l) != 0L) + jjCheckNAdd(73); + break; + case 73: + if ((0x3ff000000000000L & l) != 0L) + jjCheckNAddTwoStates(73, 10); + break; + default : break; + } + } while(i != startsAt); + } + else if (curChar < 128) + { + long l = 1L << (curChar & 077); + MatchLoop: do + { + switch(jjstateSet[--i]) + { + case 0: + case 21: + if ((0x7fffffe87fffffeL & l) == 0L) + break; + if (kind > 11) + kind = 11; + jjCheckNAdd(21); + break; + case 2: + if ((0x100000001000000L & l) != 0L) + jjCheckNAdd(3); + break; + case 3: + if ((0x7e0000007eL & l) == 0L) + break; + if (kind > 5) + kind = 5; + jjCheckNAddTwoStates(3, 4); + break; + case 4: + if ((0x100000001000L & l) != 0L && kind > 5) + kind = 5; + break; + case 7: + if ((0x2000000020L & l) != 0L) + jjAddStates(46, 47); + break; + case 10: + if ((0x5000000050L & l) != 0L && kind > 8) + kind = 8; + break; + case 12: + if ((0xffffffffefffffffL & l) != 0L) + jjCheckNAddStates(15, 17); + break; + case 13: + if (curChar == 92) + jjAddStates(48, 50); + break; + case 14: + if ((0x14404410000000L & l) != 0L) + jjCheckNAddStates(15, 17); + break; + case 24: + case 25: + if ((0x7fffffe87fffffeL & l) == 0L) + break; + if (kind > 12) + kind = 12; + jjCheckNAdd(25); + break; + case 27: + case 28: + if ((0x7fffffe87fffffeL & l) == 0L) + break; + if (kind > 13) + kind = 13; + jjCheckNAdd(28); + break; + case 31: + jjAddStates(51, 52); + break; + case 33: + jjAddStates(53, 54); + break; + case 35: + jjAddStates(55, 56); + break; + case 43: + if ((0x2000000020L & l) != 0L) + jjAddStates(57, 58); + break; + case 48: + if ((0x2000000020L & l) != 0L) + jjAddStates(59, 60); + break; + case 52: + if ((0x2000000020L & l) != 0L) + jjAddStates(61, 62); + break; + case 56: + if ((0x2000000020L & l) != 0L) + jjAddStates(63, 64); + break; + case 63: + if ((0x2000000020L & l) != 0L) + jjAddStates(65, 66); + break; + case 67: + if ((0x2000000020L & l) != 0L) + jjAddStates(67, 68); + break; + case 71: + if ((0x2000000020L & l) != 0L) + jjAddStates(69, 70); + break; + default : break; + } + } while(i != startsAt); + } + else + { + int hiByte = (int)(curChar >> 8); + int i1 = hiByte >> 6; + long l1 = 1L << (hiByte & 077); + int i2 = (curChar & 0xff) >> 6; + long l2 = 1L << (curChar & 077); + MatchLoop: do + { + switch(jjstateSet[--i]) + { + case 0: + case 21: + if (!jjCanMove_1(hiByte, i1, i2, l1, l2)) + break; + if (kind > 11) + kind = 11; + jjCheckNAdd(21); + break; + case 12: + if (jjCanMove_0(hiByte, i1, i2, l1, l2)) + jjAddStates(15, 17); + break; + case 24: + case 25: + if (!jjCanMove_1(hiByte, i1, i2, l1, l2)) + break; + if (kind > 12) + kind = 12; + jjCheckNAdd(25); + break; + case 27: + case 28: + if (!jjCanMove_1(hiByte, i1, i2, l1, l2)) + break; + if (kind > 13) + kind = 13; + jjCheckNAdd(28); + break; + case 31: + if (jjCanMove_0(hiByte, i1, i2, l1, l2)) + jjAddStates(51, 52); + break; + case 33: + if (jjCanMove_0(hiByte, i1, i2, l1, l2)) + jjAddStates(53, 54); + break; + case 35: + if (jjCanMove_0(hiByte, i1, i2, l1, l2)) + jjAddStates(55, 56); + break; + default : break; + } + } while(i != startsAt); + } + if (kind != 0x7fffffff) + { + jjmatchedKind = kind; + jjmatchedPos = curPos; + kind = 0x7fffffff; + } + ++curPos; + if ((i = jjnewStateCnt) == (startsAt = 74 - (jjnewStateCnt = startsAt))) + return curPos; + try { curChar = input_stream.readChar(); } + catch(java.io.IOException e) { return curPos; } + } +} +private final int jjStopStringLiteralDfa_1(int pos, long active0) +{ + switch (pos) + { + default : + return -1; + } +} +private final int jjStartNfa_1(int pos, long active0) +{ + return jjMoveNfa_1(jjStopStringLiteralDfa_1(pos, active0), pos + 1); +} +private final int jjStartNfaWithStates_1(int pos, int kind, int state) +{ + jjmatchedKind = kind; + jjmatchedPos = pos; + try { curChar = input_stream.readChar(); } + catch(java.io.IOException e) { return pos + 1; } + return jjMoveNfa_1(state, pos + 1); +} +private final int jjMoveStringLiteralDfa0_1() +{ + switch(curChar) + { + case 62: + return jjStopAtPos(0, 23); + default : + return jjMoveNfa_1(0, 0); + } +} +private final int jjMoveNfa_1(int startState, int curPos) +{ + int[] nextStates; + int startsAt = 0; + jjnewStateCnt = 1; + int i = 1; + jjstateSet[0] = startState; + int j, kind = 0x7fffffff; + for (;;) + { + if (++jjround == 0x7fffffff) + ReInitRounds(); + if (curChar < 64) + { + long l = 1L << curChar; + MatchLoop: do + { + switch(jjstateSet[--i]) + { + case 0: + if ((0xbfffffffffffffffL & l) != 0L) + kind = 22; + break; + default : break; + } + } while(i != startsAt); + } + else if (curChar < 128) + { + long l = 1L << (curChar & 077); + MatchLoop: do + { + switch(jjstateSet[--i]) + { + case 0: + kind = 22; + break; + default : break; + } + } while(i != startsAt); + } + else + { + int hiByte = (int)(curChar >> 8); + int i1 = hiByte >> 6; + long l1 = 1L << (hiByte & 077); + int i2 = (curChar & 0xff) >> 6; + long l2 = 1L << (curChar & 077); + MatchLoop: do + { + switch(jjstateSet[--i]) + { + case 0: + if (jjCanMove_0(hiByte, i1, i2, l1, l2) && kind > 22) + kind = 22; + break; + default : break; + } + } while(i != startsAt); + } + if (kind != 0x7fffffff) + { + jjmatchedKind = kind; + jjmatchedPos = curPos; + kind = 0x7fffffff; + } + ++curPos; + if ((i = jjnewStateCnt) == (startsAt = 1 - (jjnewStateCnt = startsAt))) + return curPos; + try { curChar = input_stream.readChar(); } + catch(java.io.IOException e) { return curPos; } + } +} +static final int[] jjnextStates = { + 39, 4, 60, 61, 66, 67, 70, 71, 10, 31, 32, 33, 34, 35, 37, 12, + 13, 15, 39, 1, 40, 46, 51, 55, 6, 7, 10, 12, 13, 17, 15, 42, + 43, 10, 47, 48, 10, 55, 56, 10, 62, 63, 10, 70, 71, 10, 8, 9, + 14, 16, 18, 31, 32, 33, 34, 35, 37, 44, 45, 49, 50, 53, 54, 57, + 58, 64, 65, 68, 69, 72, 73, +}; +private static final boolean jjCanMove_0(int hiByte, int i1, int i2, long l1, long l2) +{ + switch(hiByte) + { + case 0: + return ((jjbitVec2[i2] & l2) != 0L); + default : + if ((jjbitVec0[i1] & l1) != 0L) + return true; + return false; + } +} +private static final boolean jjCanMove_1(int hiByte, int i1, int i2, long l1, long l2) +{ + switch(hiByte) + { + case 0: + return ((jjbitVec4[i2] & l2) != 0L); + case 48: + return ((jjbitVec5[i2] & l2) != 0L); + case 49: + return ((jjbitVec6[i2] & l2) != 0L); + case 51: + return ((jjbitVec7[i2] & l2) != 0L); + case 61: + return ((jjbitVec8[i2] & l2) != 0L); + default : + if ((jjbitVec3[i1] & l1) != 0L) + return true; + return false; + } +} +public static final String[] jjstrLiteralImages = { +"", null, null, null, null, null, null, null, null, null, null, null, null, +null, null, null, "\173", "\175", "\133", "\135", "\74\74", "\76\76", null, null, +"\74", }; +public static final String[] lexStateNames = { + "DEFAULT", + "WITHINSTRING", +}; +public static final int[] jjnewLexState = { + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, +}; +static final long[] jjtoToken = { + 0x1bf3d21L, +}; +static final long[] jjtoSkip = { + 0x1eL, +}; +static final long[] jjtoMore = { + 0x400000L, +}; +private JavaCharStream input_stream; +private final int[] jjrounds = new int[74]; +private final int[] jjstateSet = new int[148]; +StringBuffer image; +int jjimageLen; +int lengthOfMatch; +protected char curChar; +public PAParserTokenManager(JavaCharStream stream) +{ + if (JavaCharStream.staticFlag) + throw new Error("ERROR: Cannot use a static CharStream class with a non-static lexical analyzer."); + input_stream = stream; +} +public PAParserTokenManager(JavaCharStream stream, int lexState) +{ + this(stream); + SwitchTo(lexState); +} +public void ReInit(JavaCharStream stream) +{ + jjmatchedPos = jjnewStateCnt = 0; + curLexState = defaultLexState; + input_stream = stream; + ReInitRounds(); +} +private final void ReInitRounds() +{ + int i; + jjround = 0x80000001; + for (i = 74; i-- > 0;) + jjrounds[i] = 0x80000000; +} +public void ReInit(JavaCharStream stream, int lexState) +{ + ReInit(stream); + SwitchTo(lexState); +} +public void SwitchTo(int lexState) +{ + if (lexState >= 2 || lexState < 0) + throw new TokenMgrError("Error: Ignoring invalid lexical state : " + lexState + ". State unchanged.", TokenMgrError.INVALID_LEXICAL_STATE); + else + curLexState = lexState; +} + +private final Token jjFillToken() +{ + Token t = Token.newToken(jjmatchedKind); + t.kind = jjmatchedKind; + String im = jjstrLiteralImages[jjmatchedKind]; + t.image = (im == null) ? input_stream.GetImage() : im; + t.beginLine = input_stream.getBeginLine(); + t.beginColumn = input_stream.getBeginColumn(); + t.endLine = input_stream.getEndLine(); + t.endColumn = input_stream.getEndColumn(); + return t; +} + +int curLexState = 0; +int defaultLexState = 0; +int jjnewStateCnt; +int jjround; +int jjmatchedPos; +int jjmatchedKind; + +public final Token getNextToken() +{ + int kind; + Token specialToken = null; + Token matchedToken; + int curPos = 0; + + EOFLoop : + for (;;) + { + try + { + curChar = input_stream.BeginToken(); + } + catch(java.io.IOException e) + { + jjmatchedKind = 0; + matchedToken = jjFillToken(); + return matchedToken; + } + image = null; + jjimageLen = 0; + + for (;;) + { + switch(curLexState) + { + case 0: + jjmatchedKind = 0x7fffffff; + jjmatchedPos = 0; + curPos = jjMoveStringLiteralDfa0_0(); + break; + case 1: + jjmatchedKind = 0x7fffffff; + jjmatchedPos = 0; + curPos = jjMoveStringLiteralDfa0_1(); + break; + } + if (jjmatchedKind != 0x7fffffff) + { + if (jjmatchedPos + 1 < curPos) + input_stream.backup(curPos - jjmatchedPos - 1); + if ((jjtoToken[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L) + { + matchedToken = jjFillToken(); + TokenLexicalActions(matchedToken); + if (jjnewLexState[jjmatchedKind] != -1) + curLexState = jjnewLexState[jjmatchedKind]; + return matchedToken; + } + else if ((jjtoSkip[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L) + { + if (jjnewLexState[jjmatchedKind] != -1) + curLexState = jjnewLexState[jjmatchedKind]; + continue EOFLoop; + } + jjimageLen += jjmatchedPos + 1; + if (jjnewLexState[jjmatchedKind] != -1) + curLexState = jjnewLexState[jjmatchedKind]; + curPos = 0; + jjmatchedKind = 0x7fffffff; + try { + curChar = input_stream.readChar(); + continue; + } + catch (java.io.IOException e1) { } + } + int error_line = input_stream.getEndLine(); + int error_column = input_stream.getEndColumn(); + String error_after = null; + boolean EOFSeen = false; + try { input_stream.readChar(); input_stream.backup(1); } + catch (java.io.IOException e1) { + EOFSeen = true; + error_after = curPos <= 1 ? "" : input_stream.GetImage(); + if (curChar == '\n' || curChar == '\r') { + error_line++; + error_column = 0; + } + else + error_column++; + } + if (!EOFSeen) { + input_stream.backup(1); + error_after = curPos <= 1 ? "" : input_stream.GetImage(); + } + throw new TokenMgrError(EOFSeen, curLexState, error_line, error_column, error_after, curChar, TokenMgrError.LEXICAL_ERROR); + } + } +} + +final void TokenLexicalActions(Token matchedToken) +{ + switch(jjmatchedKind) + { + case 23 : + if (image == null) + image = new StringBuffer(new String(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1)))); + else + image.append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1))); + matchedToken.image=image.toString().substring(0,image.toString().length()-1); + break; + default : + break; + } +} +} diff --git a/src/main/java/com/lowagie/text/pdf/codec/postscript/PAPencil.java b/src/main/java/com/lowagie/text/pdf/codec/postscript/PAPencil.java new file mode 100644 index 0000000..5612603 --- /dev/null +++ b/src/main/java/com/lowagie/text/pdf/codec/postscript/PAPencil.java @@ -0,0 +1,431 @@ +/* + * Copyright 1998 by Sun Microsystems, Inc., + * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A. + * All rights reserved. + * + * This software is the confidential and proprietary information + * of Sun Microsystems, Inc. ("Confidential Information"). You + * shall not disclose such Confidential Information and shall use + * it only in accordance with the terms of the license agreement + * you entered into with Sun. + */ + +package com.lowagie.text.pdf.codec.postscript; + +import java.util.*; +import java.awt.*; +import java.awt.font.*; +import java.awt.geom.*; +import com.lowagie.text.pdf.PdfContentByte; +import com.lowagie.text.pdf.PdfGraphics2D; + + +public class PAPencil { + + static protected class State implements Cloneable { + public Stroke stroke; + public Paint paint; + public AffineTransform at; + public Shape clipShape; + public Font font; + public Composite composite; + public GeneralPath path; + + public State(){ + this(null); + } + + public State(Graphics2D g){ + if(g == null){ + this.stroke = new BasicStroke(); + this.paint = Color.black; + this.at = new AffineTransform(); + this.font = new Font("SansSerif", Font.PLAIN, 12); + this.composite = AlphaComposite.getInstance(AlphaComposite.DST_OVER, 1.0f); + this.clipShape = null; + } else { + this.recordState(g); + } + this.path = new GeneralPath(); + } + + public void recordState(Graphics2D g){ + this.stroke = g.getStroke(); + this.paint = g.getPaint(); + this.at = g.getTransform(); + this.font = g.getFont(); + this.composite = g.getComposite(); + this.clipShape = g.getClip(); + } + + public void stampState(Graphics2D g, Dimension size){ + g.setTransform(new AffineTransform()); + g.setClip(new Rectangle(0, 0, size.width, size.height)); + g.setStroke(this.stroke); + g.setPaint(this.paint); + g.setTransform(this.at); + g.setFont(this.font); + g.setComposite(this.composite); + if(this.clipShape != null){ + g.clip(this.clipShape); + } + } + + public Object clone(){ + try { + State n = (State)super.clone(); + + n.at = (AffineTransform) this.at.clone(); + n.path = new GeneralPath(); + n.path.append(this.path, false); + return n; + } catch(CloneNotSupportedException e){ + throw new InternalError(); + } + } + + } + + // + // Class Variables + // + + // + // Instance Variables + // + + /** + * The canvas size. + */ + protected Dimension size; + + /** + * The current graphics state. + */ + protected State state; + + /** + * The stack of graphic states. + */ + protected Stack gStack; + + /** + * The font hashtable with postscript names as keys + */ + protected HashMap fonts; + + /** + * The current graphics device + */ + public Graphics2D graphics; + + // + // Constructors + // + + public PAPencil(Component component){ + this.graphics = (Graphics2D) component.getGraphics(); + this.size = component.getSize(); + this.initgraphics(); + } + + public PAPencil(Graphics graphics, Dimension size){ + this.graphics = (Graphics2D) graphics; + this.size = size; + this.initgraphics(); + } + + // + // Graphics state management + // + + public void gsave(){ + this.state.recordState(this.graphics); + State next = (State) this.state.clone(); + + this.gStack.push(this.state); + this.state = next; + } + + public void grestore(){ + if(this.gStack.empty()){ + this.initgraphics(); + } else { + this.state = (State) this.gStack.pop(); + this.state.stampState(this.graphics, this.size); + } + } + + public void grestoreall(){ + this.initgraphics(); + } + + public void initgraphics(){ + AffineTransform at = new AffineTransform(); + // turn anti-aliasing and high-quality rendering on + this.graphics.setRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)); + this.graphics.setRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY)); + + // initialize to a postscript coordinate system + at.translate(0, this.size.getHeight()); + at.scale(1, -1); + this.graphics.setTransform(at); + // this.graphics.translate(0, this.size.getHeight()); + // this.graphics.scale(1, -1); + + // state, stack and page + this.state = new State(this.graphics); + this.gStack = new Stack(); + this.erasepage(); + } + + // + // Path definition + // + + public void newpath(){ + this.state.path.reset(); + } + + public void moveto(double x, double y){ + this.state.path.moveTo((float) x, (float) y); + } + + public void moveto(Point2D p) { + this.moveto(p.getX(), p.getY()); + } + + public void rmoveto(double dx, double dy) throws PainterException { + Point2D currentPoint = this.state.path.getCurrentPoint(); + + if(currentPoint == null){ + throw new PainterException("no current point"); + } + this.state.path.moveTo((float) (currentPoint.getX() + dx) , (float) (currentPoint.getY() + dy)); + } + + public void lineto(double x, double y) throws PainterException { + Point2D currentPoint = this.state.path.getCurrentPoint(); + + if(currentPoint == null){ + throw new PainterException("no current point"); + } + this.state.path.lineTo((float) x, (float) y); + } + + public void lineto(Point2D p) throws PainterException { + this.lineto(p.getX(), p.getY()); + } + + public void rlineto(double dx, double dy) throws PainterException { + Point2D currentPoint = this.state.path.getCurrentPoint(); + + if(currentPoint == null){ + throw new PainterException("no current point"); + } + this.state.path.lineTo((float) (currentPoint.getX() + dx) , (float) (currentPoint.getY() + dy)); + } + + /** + * + * @param cx double Centerpoint x + * @param cy double Centerpoint y + * @param r double Radius r + * @param ang1 double first angle + * @param ang2 double second angle + */ + public void arc(double cx, double cy, double r, double ang1, double ang2){ + Arc2D.Float arc = new Arc2D.Float((float) ( cx - r ), (float) ( cy + - r ), (float) r * 2f, (float) r * 2f,- (float) ang1,- (float) ( ang2 - + ang1 ), Arc2D.OPEN ); + Point2D currentPoint = this.state.path.getCurrentPoint(); + if(currentPoint == null){ + this.state.path.append(arc, false); + } else { + this.state.path.append(arc, true); + } + } + + public void arcn(double cx, double cy, double r, double ang1, double ang2) { + Arc2D.Float arc = new Arc2D.Float((float) ( cx - r ), (float) + ( cy - r ), (float) r * 2f, (float) r * 2f,- (float) ang1, -(float) ( + ang2 - ang1 ), Arc2D.OPEN ); + Point2D currentPoint = this.state.path.getCurrentPoint(); + if(currentPoint == null){ + this.state.path.append(arc, false); + } else { + this.state.path.append(arc, true); + } + } + + public void curveto(double x1, double y1, double x2, double y2, + double x3, double y3) throws PainterException { + Point2D currentPoint = this.state.path.getCurrentPoint(); + + if(currentPoint == null){ + throw new PainterException("no current point"); + } + this.state.path.curveTo((float) x1, (float) y1, (float) x2, (float) y2, + (float) x3, (float) y3); + } + + public void rcurveto(double dx1, double dy1, double dx2, double dy2, + double dx3, double dy3) throws PainterException { + Point2D currentPoint = this.state.path.getCurrentPoint(); + + if(currentPoint == null){ + throw new PainterException("no current point"); + } + double x0 = currentPoint.getX(); + double y0 = currentPoint.getY(); + this.curveto(x0 + dx1, y0 + dy1, x0 + dx2, y0 + dy2, x0 + dx3,y0 + dy3); + } + + public void closepath(){ + this.state.path.closePath(); + } + + // PENDING(uweh): just a placeholder for now + public void clippath(){ + this.rectpath(0.0d, 0.0d, size.width, size.height); + } + public void clip(){ + PdfGraphics2D pdfg2d = (PdfGraphics2D) this.graphics; + pdfg2d.clip(this.state.path); + this.newpath(); +// Area currentclip=new Area(this.state.clipShape); +// Area addclip=new Area(this.state.path.createTransformedShape(AffineTransform.getTranslateInstance(0,0))); +// currentclip.intersect(addclip); +// this.graphics.clip(currentclip ); + } + public void erasepage(){ + this.graphics.clearRect(0, 0, size.width, size.height); + } + + public void charpath(String aString, boolean adjustForStroking)throws PainterException{ + FontRenderContext frc=this.graphics.getFontRenderContext(); + Font fn=this.state.font; +// System.out.println("Fonthoehe:"+fn.getSize2D()); + GlyphVector glyphVector = fn.createGlyphVector(frc, aString); + Point2D currentPoint = this.state.path.getCurrentPoint(); + Shape glyphShape = glyphVector.getOutline(); + AffineTransform currentTransform = AffineTransform.getScaleInstance(1,-1); + glyphShape=currentTransform.createTransformedShape(glyphShape); + AffineTransform currentTransform2 = AffineTransform.getTranslateInstance((float)currentPoint.getX(),(float)currentPoint.getY()); + glyphShape=currentTransform2.createTransformedShape(glyphShape); + this.state.path.append(glyphShape, false); + } + + public void showpage(){ + PdfGraphics2D pdfg2d = (PdfGraphics2D) this.graphics; + PdfContentByte cb = pdfg2d.getContent(); + try { + cb.getPdfWriter().newPage(); + } + catch (com.lowagie.text.DocumentException ex) { + ex.printStackTrace(); + } + } + + public void show(String string) throws PainterException { + Point2D currentPoint = this.state.path.getCurrentPoint(); + AffineTransform currentTransform = this.graphics.getTransform(); + Point2D tranformedPoint = currentTransform.transform(currentPoint, null); + + if(currentPoint == null){ + throw new PainterException("no current point"); + } + this.graphics.setTransform(new AffineTransform()); + this.graphics.drawString(string, (float) tranformedPoint.getX(), (float) tranformedPoint.getY()); + this.graphics.setTransform(currentTransform); + } + + public void fill(){ + this.graphics.fill(this.state.path); + this.newpath(); + } + + public void eofill(){ + this.state.path.setWindingRule(GeneralPath.WIND_EVEN_ODD); + this.graphics.fill(this.state.path); + this.state.path.setWindingRule(GeneralPath.WIND_NON_ZERO); + this.newpath(); + } + + public void stroke()throws PainterException{ + this.graphics.draw(this.state.path); + this.newpath(); + + } + + public void rectfill(double x, double y, double width, double height){ + this.gsave(); + this.rectpath(x, y, width, height); + this.fill(); + this.grestore(); + } + + public void rectfill(Rectangle2D rect){ + this.rectfill(rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight()); + } + + public void rectstroke(double x, double y, double width, double height)throws PainterException{ + this.gsave(); + this.rectpath(x, y, width, height); + this.stroke(); + this.grestore(); + } + + public void rectstroke(Rectangle2D rect)throws PainterException{ + this.rectstroke(rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight()); + } + + public void rectpath(double x, double y, double width, double height){ + this.newpath(); + this.moveto(x, y); + try { + this.rlineto(width, 0); + this.rlineto(0, height); + this.rlineto(-width, 0); + } catch(PainterException e){ + } + this.closepath(); + } + + // convenience + + // this guy tries to find an appropiate font + // if he fails returns whatever font he wants + public Font findFont(String fontname){ + Font result; + StringBuffer buffer = new StringBuffer(fontname); + int i, n; + n = buffer.length(); + + for(i = 0; i < n; i++){ + if(buffer.charAt(i) == '-'){ + buffer.setCharAt(i,' '); + } + } + + fontname = buffer.toString(); + + if(this.fonts == null){ + // construct the fonts dictionary + GraphicsEnvironment genv = GraphicsEnvironment.getLocalGraphicsEnvironment(); + Font[] fontArray = genv.getAllFonts(); + this.fonts = new HashMap(); + for(i = 0; i < fontArray.length; i++){ + String postscriptName = fontArray[i].getPSName(); + this.fonts.put(postscriptName, fontArray[i]); + } + } + result = (Font) this.fonts.get(fontname); + if(result == null){ +// result = new Font("SansSerif", Font.PLAIN, 12); + result = new Font("Arial", Font.PLAIN, 12); + } + return result; + } +} + diff --git a/src/main/java/com/lowagie/text/pdf/codec/postscript/PAToken.java b/src/main/java/com/lowagie/text/pdf/codec/postscript/PAToken.java new file mode 100644 index 0000000..52f347e --- /dev/null +++ b/src/main/java/com/lowagie/text/pdf/codec/postscript/PAToken.java @@ -0,0 +1,66 @@ +/* + * Copyright 1998 by Sun Microsystems, Inc., + * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A. + * All rights reserved. + * + * This software is the confidential and proprietary information + * of Sun Microsystems, Inc. ("Confidential Information"). You + * shall not disclose such Confidential Information and shall use + * it only in accordance with the terms of the license agreement + * you entered into with Sun. + */ + +package com.lowagie.text.pdf.codec.postscript; + +public class PAToken { + + static public final int IDENTIFIER = 0; + static public final int KEY = 1; + static public final int PROCEDURE = 2; + static public final int MARK = 3; + static public final int START_PROCEDURE = 4; + static public final int END_PROCEDURE = 5; + static public final int IMMEDIATE = 6; + static public final int START_ARRAY = 7; + static public final int END_ARRAY = 8; + static public final int START_DICT = 9; + static public final int END_DICT = 10; + + public Object value; + public int type; + + public PAToken(Object value, int type) { + super(); + this.value = value; + this.type = type; + } + + public String toString() { + switch (this.type) { + case IDENTIFIER: + return "IDENTIFIER " + this.value.toString(); + case KEY: + return "KEY " + this.value.toString(); + case PROCEDURE: + return "PROCEDURE " + this.value.toString(); + case MARK: + return "MARK"; + case START_PROCEDURE: + return "START_PROCEDURE"; + case END_PROCEDURE: + return "END_PROCEDURE"; + case IMMEDIATE: + return "IMMEDIATE " + this.value.toString(); + case START_ARRAY: + return "START_ARRAY"; + case END_ARRAY: + return "END_ARRAY"; + case START_DICT: + return "START_DICT"; + case END_DICT: + return "END_DICT"; + } + return this.value.toString(); + } + +} diff --git a/src/main/java/com/lowagie/text/pdf/codec/postscript/PainterException.java b/src/main/java/com/lowagie/text/pdf/codec/postscript/PainterException.java new file mode 100644 index 0000000..236eece --- /dev/null +++ b/src/main/java/com/lowagie/text/pdf/codec/postscript/PainterException.java @@ -0,0 +1,20 @@ +/* + * Copyright 1998 by Sun Microsystems, Inc., + * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A. + * All rights reserved. + * + * This software is the confidential and proprietary information + * of Sun Microsystems, Inc. ("Confidential Information"). You + * shall not disclose such Confidential Information and shall use + * it only in accordance with the terms of the license agreement + * you entered into with Sun. + */ + +package com.lowagie.text.pdf.codec.postscript; + +public class PainterException extends Exception { + + public PainterException(String msg){ + super(msg); + } +} diff --git a/src/main/java/com/lowagie/text/pdf/codec/postscript/ParseException.java b/src/main/java/com/lowagie/text/pdf/codec/postscript/ParseException.java new file mode 100644 index 0000000..4bf572e --- /dev/null +++ b/src/main/java/com/lowagie/text/pdf/codec/postscript/ParseException.java @@ -0,0 +1,192 @@ +/* Generated By:JavaCC: Do not edit this line. ParseException.java Version 2.1 */ +package com.lowagie.text.pdf.codec.postscript; + +/** + * This exception is thrown when parse errors are encountered. + * You can explicitly create objects of this exception type by + * calling the method generateParseException in the generated + * parser. + * + * You can modify this class to customize your error reporting + * mechanisms so long as you retain the public fields. + */ +public class ParseException extends Exception { + + /** + * This constructor is used by the method "generateParseException" + * in the generated parser. Calling this constructor generates + * a new object of this type with the fields "currentToken", + * "expectedTokenSequences", and "tokenImage" set. The boolean + * flag "specialConstructor" is also set to true to indicate that + * this constructor was used to create this object. + * This constructor calls its super class with the empty string + * to force the "toString" method of parent class "Throwable" to + * print the error message in the form: + * ParseException: + */ + public ParseException(Token currentTokenVal, + int[][] expectedTokenSequencesVal, + String[] tokenImageVal + ) + { + super(""); + specialConstructor = true; + currentToken = currentTokenVal; + expectedTokenSequences = expectedTokenSequencesVal; + tokenImage = tokenImageVal; + } + + /** + * The following constructors are for use by you for whatever + * purpose you can think of. Constructing the exception in this + * manner makes the exception behave in the normal way - i.e., as + * documented in the class "Throwable". The fields "errorToken", + * "expectedTokenSequences", and "tokenImage" do not contain + * relevant information. The JavaCC generated code does not use + * these constructors. + */ + + public ParseException() { + super(); + specialConstructor = false; + } + + public ParseException(String message) { + super(message); + specialConstructor = false; + } + + /** + * This variable determines which constructor was used to create + * this object and thereby affects the semantics of the + * "getMessage" method (see below). + */ + protected boolean specialConstructor; + + /** + * This is the last token that has been consumed successfully. If + * this object has been created due to a parse error, the token + * followng this token will (therefore) be the first error token. + */ + public Token currentToken; + + /** + * Each entry in this array is an array of integers. Each array + * of integers represents a sequence of tokens (by their ordinal + * values) that is expected at this point of the parse. + */ + public int[][] expectedTokenSequences; + + /** + * This is a reference to the "tokenImage" array of the generated + * parser within which the parse error occurred. This array is + * defined in the generated ...Constants interface. + */ + public String[] tokenImage; + + /** + * This method has the standard behavior when this object has been + * created using the standard constructors. Otherwise, it uses + * "currentToken" and "expectedTokenSequences" to generate a parse + * error message and returns it. If this object has been created + * due to a parse error, and you do not catch it (it gets thrown + * from the parser), then this method is called during the printing + * of the final stack trace, and hence the correct error message + * gets displayed. + */ + public String getMessage() { + if (!specialConstructor) { + return super.getMessage(); + } + String expected = ""; + int maxSize = 0; + for (int i = 0; i < expectedTokenSequences.length; i++) { + if (maxSize < expectedTokenSequences[i].length) { + maxSize = expectedTokenSequences[i].length; + } + for (int j = 0; j < expectedTokenSequences[i].length; j++) { + expected += tokenImage[expectedTokenSequences[i][j]] + " "; + } + if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) { + expected += "..."; + } + expected += eol + " "; + } + String retval = "Encountered \""; + Token tok = currentToken.next; + for (int i = 0; i < maxSize; i++) { + if (i != 0) retval += " "; + if (tok.kind == 0) { + retval += tokenImage[0]; + break; + } + retval += add_escapes(tok.image); + tok = tok.next; + } + retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn; + retval += "." + eol; + if (expectedTokenSequences.length == 1) { + retval += "Was expecting:" + eol + " "; + } else { + retval += "Was expecting one of:" + eol + " "; + } + retval += expected; + return retval; + } + + /** + * The end of line string for this machine. + */ + protected String eol = System.getProperty("line.separator", "\n"); + + /** + * Used to convert raw characters to their escaped version + * when these raw version cannot be used as part of an ASCII + * string literal. + */ + protected String add_escapes(String str) { + StringBuffer retval = new StringBuffer(); + char ch; + for (int i = 0; i < str.length(); i++) { + switch (str.charAt(i)) + { + case 0 : + continue; + case '\b': + retval.append("\\b"); + continue; + case '\t': + retval.append("\\t"); + continue; + case '\n': + retval.append("\\n"); + continue; + case '\f': + retval.append("\\f"); + continue; + case '\r': + retval.append("\\r"); + continue; + case '\"': + retval.append("\\\""); + continue; + case '\'': + retval.append("\\\'"); + continue; + case '\\': + retval.append("\\\\"); + continue; + default: + if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) { + String s = "0000" + Integer.toString(ch, 16); + retval.append("\\u" + s.substring(s.length() - 4, s.length())); + } else { + retval.append(ch); + } + continue; + } + } + return retval.toString(); + } + +} diff --git a/src/main/java/com/lowagie/text/pdf/codec/postscript/Token.java b/src/main/java/com/lowagie/text/pdf/codec/postscript/Token.java new file mode 100644 index 0000000..530e4de --- /dev/null +++ b/src/main/java/com/lowagie/text/pdf/codec/postscript/Token.java @@ -0,0 +1,81 @@ +/* Generated By:JavaCC: Do not edit this line. Token.java Version 2.1 */ +package com.lowagie.text.pdf.codec.postscript; + +/** + * Describes the input token stream. + */ + +public class Token { + + /** + * An integer that describes the kind of this token. This numbering + * system is determined by JavaCCParser, and a table of these numbers is + * stored in the file ...Constants.java. + */ + public int kind; + + /** + * beginLine and beginColumn describe the position of the first character + * of this token; endLine and endColumn describe the position of the + * last character of this token. + */ + public int beginLine, beginColumn, endLine, endColumn; + + /** + * The string image of the token. + */ + public String image; + + /** + * A reference to the next regular (non-special) token from the input + * stream. If this is the last token from the input stream, or if the + * token manager has not read tokens beyond this one, this field is + * set to null. This is true only if this token is also a regular + * token. Otherwise, see below for a description of the contents of + * this field. + */ + public Token next; + + /** + * This field is used to access special tokens that occur prior to this + * token, but after the immediately preceding regular (non-special) token. + * If there are no such special tokens, this field is set to null. + * When there are more than one such special token, this field refers + * to the last of these special tokens, which in turn refers to the next + * previous special token through its specialToken field, and so on + * until the first special token (whose specialToken field is null). + * The next fields of special tokens refer to other special tokens that + * immediately follow it (without an intervening regular token). If there + * is no such token, this field is null. + */ + public Token specialToken; + + /** + * Returns the image. + */ + public final String toString() + { + return image; + } + + /** + * Returns a new Token object, by default. However, if you want, you + * can create and return subclass objects based on the value of ofKind. + * Simply add the cases to the switch for all those special cases. + * For example, if you have a subclass of Token called IDToken that + * you want to create if ofKind is ID, simlpy add something like : + * + * case MyParserConstants.ID : return new IDToken(); + * + * to the following switch statement. Then you can cast matchedToken + * variable to the appropriate type and use it in your lexical actions. + */ + public static final Token newToken(int ofKind) + { + switch(ofKind) + { + default : return new Token(); + } + } + +} diff --git a/src/main/java/com/lowagie/text/pdf/codec/postscript/TokenMgrError.java b/src/main/java/com/lowagie/text/pdf/codec/postscript/TokenMgrError.java new file mode 100644 index 0000000..6b54bfa --- /dev/null +++ b/src/main/java/com/lowagie/text/pdf/codec/postscript/TokenMgrError.java @@ -0,0 +1,133 @@ +/* Generated By:JavaCC: Do not edit this line. TokenMgrError.java Version 2.1 */ +package com.lowagie.text.pdf.codec.postscript; + +public class TokenMgrError extends Error +{ + /* + * Ordinals for various reasons why an Error of this type can be thrown. + */ + + /** + * Lexical error occured. + */ + static final int LEXICAL_ERROR = 0; + + /** + * An attempt wass made to create a second instance of a static token manager. + */ + static final int STATIC_LEXER_ERROR = 1; + + /** + * Tried to change to an invalid lexical state. + */ + static final int INVALID_LEXICAL_STATE = 2; + + /** + * Detected (and bailed out of) an infinite loop in the token manager. + */ + static final int LOOP_DETECTED = 3; + + /** + * Indicates the reason why the exception is thrown. It will have + * one of the above 4 values. + */ + int errorCode; + + /** + * Replaces unprintable characters by their espaced (or unicode escaped) + * equivalents in the given string + */ + protected static final String addEscapes(String str) { + StringBuffer retval = new StringBuffer(); + char ch; + for (int i = 0; i < str.length(); i++) { + switch (str.charAt(i)) + { + case 0 : + continue; + case '\b': + retval.append("\\b"); + continue; + case '\t': + retval.append("\\t"); + continue; + case '\n': + retval.append("\\n"); + continue; + case '\f': + retval.append("\\f"); + continue; + case '\r': + retval.append("\\r"); + continue; + case '\"': + retval.append("\\\""); + continue; + case '\'': + retval.append("\\\'"); + continue; + case '\\': + retval.append("\\\\"); + continue; + default: + if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) { + String s = "0000" + Integer.toString(ch, 16); + retval.append("\\u" + s.substring(s.length() - 4, s.length())); + } else { + retval.append(ch); + } + continue; + } + } + return retval.toString(); + } + + /** + * Returns a detailed message for the Error when it is thrown by the + * token manager to indicate a lexical error. + * Parameters : + * EOFSeen : indicates if EOF caused the lexicl error + * curLexState : lexical state in which this error occured + * errorLine : line number when the error occured + * errorColumn : column number when the error occured + * errorAfter : prefix that was seen before this error occured + * curchar : the offending character + * Note: You can customize the lexical error message by modifying this method. + */ + private static final String LexicalError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar) { + return("Lexical error at line " + + errorLine + ", column " + + errorColumn + ". Encountered: " + + (EOFSeen ? " " : ("\"" + addEscapes(String.valueOf(curChar)) + "\"") + " (" + (int)curChar + "), ") + + "after : \"" + addEscapes(errorAfter) + "\""); + } + + /** + * You can also modify the body of this method to customize your error messages. + * For example, cases like LOOP_DETECTED and INVALID_LEXICAL_STATE are not + * of end-users concern, so you can return something like : + * + * "Internal Error : Please file a bug report .... " + * + * from this method for such cases in the release version of your parser. + */ + public String getMessage() { + return super.getMessage(); + } + + /* + * Constructors of various flavors follow. + */ + + public TokenMgrError() { + } + + public TokenMgrError(String message, int reason) { + super(message); + errorCode = reason; + } + + public TokenMgrError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar, int reason) { + this(LexicalError(EOFSeen, lexState, errorLine, errorColumn, errorAfter, curChar), reason); + } +} -- cgit v1.2.3