View | Details | Raw Unified | Return to bug 41582
Collapse All | Expand All

(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/test/java/org/apache/xmlgraphics/ps/dsc/tools/DSCToolsTestCase.java (+57 lines)
Line 0 Link Here
1
/*
2
 * Licensed to the Apache Software Foundation (ASF) under one or more
3
 * contributor license agreements.  See the NOTICE file distributed with
4
 * this work for additional information regarding copyright ownership.
5
 * The ASF licenses this file to You under the Apache License, Version 2.0
6
 * (the "License"); you may not use this file except in compliance with
7
 * the License.  You may obtain a copy of the License at
8
 * 
9
 *      http://www.apache.org/licenses/LICENSE-2.0
10
 * 
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
18
/* $Id$ */
19
20
package org.apache.xmlgraphics.ps.dsc.tools;
21
22
import org.apache.xmlgraphics.ps.dsc.events.DSCCommentEndComments;
23
import org.apache.xmlgraphics.ps.dsc.events.DSCCommentPages;
24
import org.apache.xmlgraphics.ps.dsc.events.DSCEvent;
25
import org.apache.xmlgraphics.ps.dsc.events.PostScriptComment;
26
import org.apache.xmlgraphics.ps.dsc.events.PostScriptLine;
27
28
import junit.framework.TestCase;
29
30
public class DSCToolsTestCase extends TestCase {
31
32
    public void testEndComment() throws Exception {
33
        DSCEvent event;
34
        
35
        event = new DSCCommentEndComments();
36
        assertTrue(DSCTools.headerCommentsEndHere(event));
37
38
        event = new PostScriptComment("FOPTest");
39
        assertFalse(DSCTools.headerCommentsEndHere(event));
40
41
        event = new DSCCommentPages(7);
42
        assertFalse(DSCTools.headerCommentsEndHere(event));
43
44
        event = new PostScriptComment(null);
45
        assertTrue(DSCTools.headerCommentsEndHere(event));
46
47
        event = new PostScriptComment("\t");
48
        assertTrue(DSCTools.headerCommentsEndHere(event));
49
50
        event = new PostScriptComment(" ***");
51
        assertTrue(DSCTools.headerCommentsEndHere(event));
52
53
        event = new PostScriptLine("/pgsave save def");
54
        assertTrue(DSCTools.headerCommentsEndHere(event));
55
    }
56
    
57
}
0
  + native
58
  + native
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/test/java/org/apache/xmlgraphics/ps/dsc/events/DSCValueParserTestCase.java (+72 lines)
Line 0 Link Here
1
/*
2
 * Licensed to the Apache Software Foundation (ASF) under one or more
3
 * contributor license agreements.  See the NOTICE file distributed with
4
 * this work for additional information regarding copyright ownership.
5
 * The ASF licenses this file to You under the Apache License, Version 2.0
6
 * (the "License"); you may not use this file except in compliance with
7
 * the License.  You may obtain a copy of the License at
8
 * 
9
 *      http://www.apache.org/licenses/LICENSE-2.0
10
 * 
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
18
/* $Id$ */
19
20
package org.apache.xmlgraphics.ps.dsc.events;
21
22
import java.util.List;
23
24
import org.apache.xmlgraphics.ps.dsc.events.DSCCommentBeginResource;
25
26
import junit.framework.TestCase;
27
28
public class DSCValueParserTestCase extends TestCase {
29
30
    private String[] toArray(List params) {
31
        return (String[])params.toArray(new String[params.size()]);
32
    }
33
    
34
    public void testText() throws Exception {
35
        DSCCommentBeginResource obj = new DSCCommentBeginResource();
36
        String[] res = toArray(obj.splitParams("procset Test"));
37
        assertEquals(2, res.length);
38
        assertEquals("procset", res[0]);
39
        assertEquals("Test", res[1]);
40
41
        res = toArray(obj.splitParams("procset\tTest"));
42
        assertEquals(2, res.length);
43
        assertEquals("procset", res[0]);
44
        assertEquals("Test", res[1]);
45
    }
46
    
47
    public void testParentheseText() throws Exception {
48
        DSCCommentBeginResource obj = new DSCCommentBeginResource();
49
        String[] res = toArray(obj.splitParams("procset (Hello World!)"));
50
        assertEquals(2, res.length);
51
        assertEquals("procset", res[0]);
52
        assertEquals("Hello World!", res[1]);
53
54
        res = toArray(obj.splitParams("procset\t(Hello\t\\\\wonderful/ World!)"));
55
        assertEquals(2, res.length);
56
        assertEquals("procset", res[0]);
57
        assertEquals("Hello\t\\wonderful/ World!", res[1]);
58
59
        res = toArray(obj.splitParams("procset (Hello \\042wonderful\\042 World!) blahblah"));
60
        assertEquals(3, res.length);
61
        assertEquals("procset", res[0]);
62
        assertEquals("Hello \"wonderful\" World!", res[1]);
63
        assertEquals("blahblah", res[2]);
64
65
        //Parentheses not balanced
66
        res = toArray(obj.splitParams("procset (Hello (wonderful) World! blahblah"));
67
        assertEquals(2, res.length);
68
        assertEquals("procset", res[0]);
69
        assertEquals("Hello (wonderful) World! blahblah", res[1]);
70
    }
71
    
72
}
0
  + native
73
  + native
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/test/java/org/apache/xmlgraphics/StandardTestSuite.java (+4 lines)
Lines 20-25 Link Here
20
package org.apache.xmlgraphics;
20
package org.apache.xmlgraphics;
21
21
22
import org.apache.xmlgraphics.image.codec.png.PNGEncoderTest;
22
import org.apache.xmlgraphics.image.codec.png.PNGEncoderTest;
23
import org.apache.xmlgraphics.ps.dsc.events.DSCValueParserTestCase;
24
import org.apache.xmlgraphics.ps.dsc.tools.DSCToolsTestCase;
23
import org.apache.xmlgraphics.util.ServiceTest;
25
import org.apache.xmlgraphics.util.ServiceTest;
24
import org.apache.xmlgraphics.util.io.ASCII85InputStreamTestCase;
26
import org.apache.xmlgraphics.util.io.ASCII85InputStreamTestCase;
25
import org.apache.xmlgraphics.util.io.ASCII85OutputStreamTestCase;
27
import org.apache.xmlgraphics.util.io.ASCII85OutputStreamTestCase;
Lines 46-51 Link Here
46
        suite.addTest(new TestSuite(ASCII85OutputStreamTestCase.class));
48
        suite.addTest(new TestSuite(ASCII85OutputStreamTestCase.class));
47
        suite.addTest(new TestSuite(PNGEncoderTest.class));
49
        suite.addTest(new TestSuite(PNGEncoderTest.class));
48
        suite.addTest(new TestSuite(ServiceTest.class));
50
        suite.addTest(new TestSuite(ServiceTest.class));
51
        suite.addTest(new TestSuite(DSCValueParserTestCase.class));
52
        suite.addTest(new TestSuite(DSCToolsTestCase.class));
49
        //$JUnit-END$
53
        //$JUnit-END$
50
        return suite;
54
        return suite;
51
    }
55
    }
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/ps/PSProcSet.java (+69 lines)
Line 0 Link Here
1
/*
2
 * Licensed to the Apache Software Foundation (ASF) under one or more
3
 * contributor license agreements.  See the NOTICE file distributed with
4
 * this work for additional information regarding copyright ownership.
5
 * The ASF licenses this file to You under the Apache License, Version 2.0
6
 * (the "License"); you may not use this file except in compliance with
7
 * the License.  You may obtain a copy of the License at
8
 * 
9
 *      http://www.apache.org/licenses/LICENSE-2.0
10
 * 
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
18
/* $Id$ */
19
 
20
package org.apache.xmlgraphics.ps;
21
22
/**
23
 * PSResource subclass that represents a ProcSet resource.
24
 */
25
public class PSProcSet extends PSResource {
26
    
27
    private float version;
28
    private int revision;
29
    
30
    /**
31
     * Creates a new instance.
32
     * @param name name of the resource
33
     */
34
    public PSProcSet(String name) {
35
        this(name, 1.0f, 0);
36
    }
37
38
    /**
39
     * Creates a new instance.
40
     * @param name name of the resource
41
     * @param version version of the resource
42
     * @param revision revision of the resource
43
     */
44
    public PSProcSet(String name, float version, int revision) {
45
        super(TYPE_PROCSET, name);
46
        this.version = version;
47
        this.revision = revision;
48
    }
49
50
    /** @return the version */
51
    public float getVersion() {
52
        return version;
53
    }
54
55
    /** @return the revision */
56
    public int getRevision() {
57
        return revision;
58
    }
59
    
60
    /** @return the <resource> specification as defined in DSC v3.0 spec. */
61
    public String getResourceSpecification() {
62
        StringBuffer sb = new StringBuffer();
63
        sb.append(getType()).append(" ").append(PSGenerator.convertStringToDSC(getName()));
64
        sb.append(" ").append(PSGenerator.convertRealToDSC(getVersion()));
65
        sb.append(" ").append(Integer.toString(getRevision()));
66
        return sb.toString();
67
    }
68
69
}
0
  + native
70
  + native
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/ps/PSProcSets.java (-19 / +25 lines)
Lines 22-54 Link Here
22
import java.io.IOException;
22
import java.io.IOException;
23
23
24
/**
24
/**
25
 * This class defines the basic resources (procsets) used by FOP's PostScript
25
 * This class defines the basic resources (procsets) used by the Apache XML Graphics project.
26
 * renderer and SVG transcoder.
27
 * 
26
 * 
28
 * @author <a href="mailto:fop-dev@xmlgraphics.apache.org">Apache FOP Development Team</a>
29
 * @version $Id$
27
 * @version $Id$
30
 */
28
 */
31
public final class PSProcSets {
29
public final class PSProcSets {
32
30
33
    /** the standard FOP procset */
31
    /** the standard procset for the XML Graphics project */
34
    public static final PSResource STD_PROCSET = new StdProcSet();
32
    public static final PSResource STD_PROCSET = new StdProcSet();
35
    /** the EPS FOP procset */
33
    /** the EPS procset for the XML Graphics project */
36
    public static final PSResource EPS_PROCSET = new EPSProcSet();
34
    public static final PSResource EPS_PROCSET = new EPSProcSet();
37
    
35
    
38
    private static class StdProcSet extends PSResource {
36
    private static class StdProcSet extends PSProcSet {
39
        
37
        
40
        public StdProcSet() {
38
        public StdProcSet() {
41
            super("procset", "Apache FOP Std ProcSet");
39
            super("Apache XML Graphics Std ProcSet", 1.0f, 0);
42
        }
40
        }
43
        
41
        
44
        public void writeTo(PSGenerator gen) throws IOException {
42
        public void writeTo(PSGenerator gen) throws IOException {
45
            gen.writeDSCComment(DSCConstants.BEGIN_RESOURCE, 
43
            gen.writeDSCComment(DSCConstants.BEGIN_RESOURCE, 
46
                    new Object[] {"procset", getName(), "1.0", "0"});
44
                    new Object[] {TYPE_PROCSET, getName(), 
45
                        Float.toString(getVersion()), Integer.toString(getRevision())});
47
            gen.writeDSCComment(DSCConstants.VERSION, 
46
            gen.writeDSCComment(DSCConstants.VERSION, 
48
                    new Object[] {"1.0", "0"});
47
                    new Object[] {Float.toString(getVersion()), Integer.toString(getRevision())});
49
            gen.writeDSCComment(DSCConstants.COPYRIGHT, "Copyright 2001-2003 "
48
            gen.writeDSCComment(DSCConstants.COPYRIGHT, "Copyright 2001-2003 "
50
                        + "The Apache Software Foundation. All rights reserved.");
49
                        + "The Apache Software Foundation. "
51
            gen.writeDSCComment(DSCConstants.TITLE, "Basic set of procedures used by FOP");
50
                        + "License terms: http://www.apache.org/licenses/LICENSE-2.0");
51
            gen.writeDSCComment(DSCConstants.TITLE, 
52
                    "Basic set of procedures used by the XML Graphics project (Batik and FOP)");
52
53
53
            gen.writeln("/bd{bind def}bind def");
54
            gen.writeln("/bd{bind def}bind def");
54
            gen.writeln("/ld{load def}bd");
55
            gen.writeln("/ld{load def}bd");
Lines 140-163 Link Here
140
            gen.writeln("} bd");
141
            gen.writeln("} bd");
141
            
142
            
142
            gen.writeDSCComment(DSCConstants.END_RESOURCE);
143
            gen.writeDSCComment(DSCConstants.END_RESOURCE);
144
            gen.getResourceTracker().registerSuppliedResource(this);
143
        }
145
        }
144
        
146
        
145
    }
147
    }
146
148
147
    private static class EPSProcSet extends PSResource {
149
    private static class EPSProcSet extends PSProcSet {
148
        
150
        
149
        public EPSProcSet() {
151
        public EPSProcSet() {
150
            super("procset", "Apache FOP EPS ProcSet");
152
            super("Apache XML Graphics EPS ProcSet", 1.0f, 0);
151
        }
153
        }
152
        
154
        
153
        public void writeTo(PSGenerator gen) throws IOException {
155
        public void writeTo(PSGenerator gen) throws IOException {
154
            gen.writeDSCComment(DSCConstants.BEGIN_RESOURCE, 
156
            gen.writeDSCComment(DSCConstants.BEGIN_RESOURCE, 
155
                    new Object[] {"procset", getName(), "1.0", "0"});
157
                    new Object[] {TYPE_PROCSET, getName(), 
158
                        Float.toString(getVersion()), Integer.toString(getRevision())});
156
            gen.writeDSCComment(DSCConstants.VERSION, 
159
            gen.writeDSCComment(DSCConstants.VERSION, 
157
                    new Object[] {"1.0", "0"});
160
                    new Object[] {Float.toString(getVersion()), Integer.toString(getRevision())});
158
            gen.writeDSCComment(DSCConstants.COPYRIGHT, "Copyright 2002-2003 "
161
            gen.writeDSCComment(DSCConstants.COPYRIGHT, "Copyright 2002-2003 "
159
                        + "The Apache Software Foundation. All rights reserved.");
162
                    + "The Apache Software Foundation. "
160
            gen.writeDSCComment(DSCConstants.TITLE, "EPS procedures used by FOP");
163
                    + "License terms: http://www.apache.org/licenses/LICENSE-2.0");
164
            gen.writeDSCComment(DSCConstants.TITLE, 
165
                    "EPS procedures used by the Apache XML Graphics project (Batik and FOP)");
161
166
162
            gen.writeln("/BeginEPSF { %def");
167
            gen.writeln("/BeginEPSF { %def");
163
            gen.writeln("/b4_Inc_state save def         % Save state for cleanup");
168
            gen.writeln("/b4_Inc_state save def         % Save state for cleanup");
Lines 183-188 Link Here
183
            gen.writeln("} bd");
188
            gen.writeln("} bd");
184
            
189
            
185
            gen.writeDSCComment(DSCConstants.END_RESOURCE);
190
            gen.writeDSCComment(DSCConstants.END_RESOURCE);
191
            gen.getResourceTracker().registerSuppliedResource(this);
186
        }
192
        }
187
        
193
        
188
    }
194
    }
Lines 192-198 Link Here
192
     * @param gen PSGenerator to use for output
198
     * @param gen PSGenerator to use for output
193
     * @throws IOException In case of an I/O problem
199
     * @throws IOException In case of an I/O problem
194
     */
200
     */
195
    public static void writeFOPStdProcSet(PSGenerator gen) throws IOException {
201
    public static void writeStdProcSet(PSGenerator gen) throws IOException {
196
        ((StdProcSet)STD_PROCSET).writeTo(gen);
202
        ((StdProcSet)STD_PROCSET).writeTo(gen);
197
    }
203
    }
198
204
Lines 202-208 Link Here
202
     * @param gen PSGenerator to use for output
208
     * @param gen PSGenerator to use for output
203
     * @throws IOException In case of an I/O problem
209
     * @throws IOException In case of an I/O problem
204
     */
210
     */
205
    public static void writeFOPEPSProcSet(PSGenerator gen) throws IOException {
211
    public static void writeEPSProcSet(PSGenerator gen) throws IOException {
206
        ((EPSProcSet)EPS_PROCSET).writeTo(gen);
212
        ((EPSProcSet)EPS_PROCSET).writeTo(gen);
207
    }
213
    }
208
214
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/ps/DSCConstants.java (-2 / +26 lines)
Lines 46-52 Link Here
46
    public static final String CREATION_DATE     = "CreationDate";
46
    public static final String CREATION_DATE     = "CreationDate";
47
    /** Type of data */
47
    /** Type of data */
48
    public static final String DOCUMENT_DATA     = "BoundingBox";
48
    public static final String DOCUMENT_DATA     = "BoundingBox";
49
    /** Use for inidicating an emulator being invoked in the document */
49
    /** Use for indicating an emulator being invoked in the document */
50
    public static final String EMULATION         = "Emulation";
50
    public static final String EMULATION         = "Emulation";
51
    /** Explicit end of comments */
51
    /** Explicit end of comments */
52
    public static final String END_COMMENTS      = "EndComments";
52
    public static final String END_COMMENTS      = "EndComments";
Lines 135-141 Link Here
135
    public static final String PAGE_TRAILER     = "PageTrailer";
135
    public static final String PAGE_TRAILER     = "PageTrailer";
136
    /** Indicates the start of the document trailer */    
136
    /** Indicates the start of the document trailer */    
137
    public static final String TRAILER          = "Trailer";
137
    public static final String TRAILER          = "Trailer";
138
    /** Indicates the end of a page (NON-STANDARD!) */    
138
    /**
139
     * Indicates the end of a page (NON-STANDARD!)
140
     * @deprecated Shouldn't really use that. Bad idea. "Page" and "Trailer" end a page.
141
     */    
139
    public static final String END_PAGE         = "EndPage";
142
    public static final String END_PAGE         = "EndPage";
140
    /** Indicates the end of the document */    
143
    /** Indicates the end of the document */    
141
    public static final String EOF              = "EOF";
144
    public static final String EOF              = "EOF";
Lines 216-219 Link Here
216
     */
219
     */
217
    public static final String PAGE_RESOURCES    = "PageResources";
220
    public static final String PAGE_RESOURCES    = "PageResources";
218
221
222
    // ----==== (atend) indicator ====----
223
    
224
    /** 
225
     * Indicator for the PostScript interpreter that the value is provided 
226
     * later in the document (mostly in the %%Trailer section).
227
     */
228
    public static final Object ATEND = new AtendIndicator();
229
230
    /** Used for the ATEND constant. See there. */
231
    private static final class AtendIndicator extends Object {
232
        
233
        private AtendIndicator() {
234
            super();
235
        }
236
        
237
        public String toString() {
238
            return "(atend)";
239
        }
240
    }
241
242
    
219
}
243
}
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/ps/PSImageUtils.java (-41 / +179 lines)
Lines 43-49 Link Here
43
     * Writes a bitmap image to the PostScript stream.
43
     * Writes a bitmap image to the PostScript stream.
44
     * @param img the bitmap image as a byte array
44
     * @param img the bitmap image as a byte array
45
     * @param imgDim the dimensions of the image
45
     * @param imgDim the dimensions of the image
46
     * @param imgName the name of the image
46
     * @param imgDescription the name of the image
47
     * @param targetRect the target rectangle to place the image in
47
     * @param targetRect the target rectangle to place the image in
48
     * @param isJPEG true if "img" contains a DCT-encoded images, false if "img" contains the 
48
     * @param isJPEG true if "img" contains a DCT-encoded images, false if "img" contains the 
49
     *               decoded bitmap
49
     *               decoded bitmap
Lines 52-77 Link Here
52
     * @throws IOException In case of an I/O exception
52
     * @throws IOException In case of an I/O exception
53
     */
53
     */
54
    public static void writeImage(byte[] img,
54
    public static void writeImage(byte[] img,
55
            Dimension imgDim, String imgName,
55
            Dimension imgDim, String imgDescription,
56
            Rectangle2D targetRect, 
56
            Rectangle2D targetRect, 
57
            boolean isJPEG, ColorSpace colorSpace,
57
            boolean isJPEG, ColorSpace colorSpace,
58
            PSGenerator gen) throws IOException {
58
            PSGenerator gen) throws IOException {
59
        boolean iscolor = colorSpace.getType() != ColorSpace.CS_GRAY;
60
61
        gen.saveGraphicsState();
59
        gen.saveGraphicsState();
62
        gen.writeln(gen.formatDouble(targetRect.getX()) + " " 
60
        gen.writeln(gen.formatDouble(targetRect.getX()) + " " 
63
                + gen.formatDouble(targetRect.getY()) + " translate");
61
                + gen.formatDouble(targetRect.getY()) + " translate");
64
        gen.writeln(gen.formatDouble(targetRect.getWidth()) + " " 
62
        gen.writeln(gen.formatDouble(targetRect.getWidth()) + " " 
65
                + gen.formatDouble(targetRect.getHeight()) + " scale");
63
                + gen.formatDouble(targetRect.getHeight()) + " scale");
66
64
67
        gen.commentln("%FOPBeginBitmap: " + imgName);
65
        gen.commentln("%AXGBeginBitmap: " + imgDescription);
68
        if (colorSpace.getType() == ColorSpace.TYPE_CMYK) {
69
            gen.writeln("/DeviceCMYK setcolorspace");
70
        } else if (colorSpace.getType() == ColorSpace.CS_GRAY) {
71
            gen.writeln("/DeviceGray setcolorspace");
72
        } else {
73
            gen.writeln("/DeviceRGB setcolorspace");
74
        }
75
66
76
        gen.writeln("{{");
67
        gen.writeln("{{");
77
        // Template: (RawData is used for the EOF signal only)
68
        // Template: (RawData is used for the EOF signal only)
Lines 89-96 Link Here
89
                gen.writeln("/Data RawData /RunLengthDecode filter def");
80
                gen.writeln("/Data RawData /RunLengthDecode filter def");
90
            }
81
            }
91
        }
82
        }
92
        gen.writeln("<<");
83
        writeImageCommand(imgDim, colorSpace, gen, "Data");
93
        gen.writeln("  /ImageType 1");
84
        /* the following two lines could be enabled if something still goes wrong
85
         * gen.write("Data closefile");
86
         * gen.write("RawData flushfile");
87
         */
88
        gen.writeln("} stopped {handleerror} if");
89
        gen.writeln("  RawData flushfile");
90
        gen.writeln("} exec");
91
92
        encodeBitmap(img, isJPEG, gen);
93
94
        gen.writeln("");
95
        gen.commentln("%AXGEndBitmap");
96
        gen.restoreGraphicsState();
97
    }
98
99
    private static void writeImageCommand(Dimension imgDim, ColorSpace colorSpace, 
100
            PSGenerator gen, String dataSource) throws IOException {
101
        boolean iscolor = colorSpace.getType() != ColorSpace.CS_GRAY;
102
        prepareColorspace(colorSpace, gen);
103
        gen.writeln("<< /ImageType 1");
94
        gen.writeln("  /Width " + imgDim.width);
104
        gen.writeln("  /Width " + imgDim.width);
95
        gen.writeln("  /Height " + imgDim.height);
105
        gen.writeln("  /Height " + imgDim.height);
96
        gen.writeln("  /BitsPerComponent 8");
106
        gen.writeln("  /BitsPerComponent 8");
Lines 109-125 Link Here
109
        gen.writeln("  /ImageMatrix [" + imgDim.width + " 0 0 "
119
        gen.writeln("  /ImageMatrix [" + imgDim.width + " 0 0 "
110
              + imgDim.height + " 0 0]");
120
              + imgDim.height + " 0 0]");
111
121
112
        gen.writeln("  /DataSource Data");
122
        gen.writeln("  /DataSource " + dataSource);
113
        gen.writeln(">>");
123
        gen.writeln(">> image");
114
        gen.writeln("image");
124
    }
115
        /* the following two lines could be enabled if something still goes wrong
116
         * gen.write("Data closefile");
117
         * gen.write("RawData flushfile");
118
         */
119
        gen.writeln("} stopped {handleerror} if");
120
        gen.writeln("  RawData flushfile");
121
        gen.writeln("} exec");
122
125
126
    /**
127
     * Writes a bitmap image as a PostScript form enclosed by DSC resource wrappers to the
128
     * PostScript file.
129
     * @param img the raw bitmap data
130
     * @param imgDim the dimensions of the image
131
     * @param formName the name of the PostScript form to use
132
     * @param imageDescription a description of the image added as a DSC Title comment
133
     * @param isJPEG true if "img" contains a DCT-encoded images, false if "img" contains the 
134
     *               decoded bitmap
135
     * @param colorSpace the color space of the image
136
     * @param gen the PostScript generator
137
     * @return a PSResource representing the form for resource tracking
138
     * @throws IOException In case of an I/O exception
139
     */
140
    public static PSResource writeReusableImage(byte[] img,
141
            Dimension imgDim, String formName, String imageDescription,
142
            boolean isJPEG, ColorSpace colorSpace,
143
            PSGenerator gen) throws IOException {
144
        if (gen.getPSLevel() < 2) {
145
            throw new UnsupportedOperationException(
146
                    "Reusable images requires at least Level 2 PostScript");
147
        }
148
        String dataName = formName + ":Data";
149
        gen.writeDSCComment(DSCConstants.BEGIN_RESOURCE, formName);
150
        if (imageDescription != null) {
151
            gen.writeDSCComment(DSCConstants.TITLE, imageDescription);
152
        }
153
        
154
        String additionalFilters;
155
        if (isJPEG) {
156
            additionalFilters = "/ASCII85Decode filter /DCTDecode filter";
157
        } else {
158
            if (gen.getPSLevel() >= 3) {
159
                additionalFilters = "/ASCII85Decode filter /FlateDecode filter";
160
            } else {
161
                additionalFilters = "/ASCII85Decode filter /RunLengthDecode filter";
162
            }
163
        }
164
165
        gen.writeln("/" + formName);
166
        gen.writeln("<< /FormType 1");
167
        gen.writeln("  /BBox [0 0 " + imgDim.width + " " + imgDim.height + "]");
168
        gen.writeln("  /Matrix [1 0 0 1 0 0]");
169
        gen.writeln("  /PaintProc {");
170
        gen.writeln("    pop");
171
        gen.writeln("    gsave");
172
        if (gen.getPSLevel() == 2) {
173
            gen.writeln("    userdict /i 0 put"); //rewind image data
174
        } else {
175
            gen.writeln("    " + dataName + " 0 setfileposition"); //rewind image data
176
        }
177
        String dataSource;
178
        if (gen.getPSLevel() == 2) {
179
            dataSource = "{ " + dataName + " i get /i i 1 add store } bind";
180
        } else {
181
            dataSource = dataName;
182
        }
183
        writeImageCommand(imgDim, colorSpace, gen, dataSource); 
184
        gen.writeln("    grestore");
185
        gen.writeln("  } bind");
186
        gen.writeln(">> def");
187
        gen.writeln("/" + dataName + " currentfile");
188
        gen.writeln(additionalFilters);
189
        if (gen.getPSLevel() == 2) {
190
            //Creates a data array from the inline file
191
            gen.writeln("{ /temp exch def ["
192
                    + " { temp 16384 string readstring not {exit } if } loop ] } exec");
193
        } else {
194
            gen.writeln("/ReusableStreamDecode filter");
195
        }
196
        encodeBitmap(img, isJPEG, gen);
197
        gen.writeln("def");
198
        gen.writeDSCComment(DSCConstants.END_RESOURCE);
199
        PSResource res = new PSResource(PSResource.TYPE_FORM, formName); 
200
        gen.getResourceTracker().registerSuppliedResource(res);
201
        return res;
202
    }
203
    
204
    /**
205
     * Paints a reusable image (previously added as a PostScript form).
206
     * @param formName the name of the PostScript form implementing the image
207
     * @param targetRect the target rectangle to place the image in
208
     * @param gen the PostScript generator
209
     * @throws IOException In case of an I/O exception
210
     */
211
    public static void paintReusableImage(
212
            String formName,
213
            Rectangle2D targetRect, 
214
            PSGenerator gen) throws IOException {
215
        PSResource form = new PSResource(PSResource.TYPE_FORM, formName);
216
        paintForm(form, targetRect, gen);
217
    }
218
    
219
    /**
220
     * Paints a reusable image (previously added as a PostScript form).
221
     * @param form the PostScript form resource implementing the image
222
     * @param targetRect the target rectangle to place the image in
223
     * @param gen the PostScript generator
224
     * @throws IOException In case of an I/O exception
225
     */
226
    public static void paintForm(
227
            PSResource form,
228
            Rectangle2D targetRect, 
229
            PSGenerator gen) throws IOException {
230
        gen.saveGraphicsState();
231
        gen.writeln(gen.formatDouble(targetRect.getX()) + " " 
232
                + gen.formatDouble(targetRect.getY()) + " translate");
233
        gen.writeln(gen.formatDouble(targetRect.getWidth()) + " " 
234
                + gen.formatDouble(targetRect.getHeight()) + " scale");
235
        gen.writeln(form.getName() + " execform");
236
        
237
        gen.getResourceTracker().notifyResourceUsageOnPage(form);
238
        gen.restoreGraphicsState();
239
    }
240
    
241
    private static void prepareColorspace(ColorSpace colorSpace, PSGenerator gen)
242
                throws IOException {
243
        if (colorSpace.getType() == ColorSpace.TYPE_CMYK) {
244
            gen.writeln("/DeviceCMYK setcolorspace");
245
        } else if (colorSpace.getType() == ColorSpace.CS_GRAY) {
246
            gen.writeln("/DeviceGray setcolorspace");
247
        } else {
248
            gen.writeln("/DeviceRGB setcolorspace");
249
        }
250
    }
251
252
    private static void encodeBitmap(byte[] img, boolean isJPEG, PSGenerator gen)
253
                throws IOException {
123
        OutputStream out = gen.getOutputStream();
254
        OutputStream out = gen.getOutputStream();
124
        out = new ASCII85OutputStream(out);
255
        out = new ASCII85OutputStream(out);
125
        if (isJPEG) {
256
        if (isJPEG) {
Lines 137-146 Link Here
137
        } else {
268
        } else {
138
            out.flush();
269
            out.flush();
139
        }
270
        }
140
271
        gen.newLine();
141
        gen.writeln("");
142
        gen.commentln("%FOPEndBitmap");
143
        gen.restoreGraphicsState();
144
    }
272
    }
145
273
146
    /**
274
    /**
Lines 184-194 Link Here
184
        return bitmaps;
312
        return bitmaps;
185
    }
313
    }
186
    
314
    
315
    /**
316
     * Extracts a packed RGB integer array of a RenderedImage.
317
     * @param img the image
318
     * @param startX the starting X coordinate
319
     * @param startY the starting Y coordinate
320
     * @param w the width of the cropped image
321
     * @param h the height of the cropped image
322
     * @param rgbArray the prepared integer array to write to
323
     * @param offset offset in the target array
324
     * @param scansize width of a row in the target array
325
     * @return the populated integer array previously passed in as rgbArray parameter
326
     */
187
    public static int[] getRGB(RenderedImage img,
327
    public static int[] getRGB(RenderedImage img,
188
                int startX, int startY, int w, int h,
328
                int startX, int startY,
329
                int w, int h,
189
                int[] rgbArray, int offset, int scansize) {
330
                int[] rgbArray, int offset, int scansize) {
190
        Raster raster = img.getData();
331
        Raster raster = img.getData();
191
        int yoff  = offset;
332
        int yoff = offset;
192
        int off;
333
        int off;
193
        Object data;
334
        Object data;
194
        int nbands = raster.getNumBands();
335
        int nbands = raster.getNumBands();
Lines 215-235 Link Here
215
        }
356
        }
216
        
357
        
217
        if (rgbArray == null) {
358
        if (rgbArray == null) {
218
            rgbArray = new int[offset+h*scansize];
359
            rgbArray = new int[offset + h * scansize];
219
        }
360
        }
220
        
361
        
221
        ColorModel colorModel = img.getColorModel();
362
        ColorModel colorModel = img.getColorModel();
222
        for (int y = startY; y < startY+h; y++, yoff+=scansize) {
363
        for (int y = startY; y < startY + h; y++, yoff += scansize) {
223
            off = yoff;
364
            off = yoff;
224
            for (int x = startX; x < startX+w; x++) {
365
            for (int x = startX; x < startX + w; x++) {
225
                rgbArray[off++] = colorModel.getRGB(raster.getDataElements(x,
366
                rgbArray[off++] = colorModel.getRGB(raster.getDataElements(x, y, data));
226
                                    y,
227
                                    data));
228
            }
367
            }
229
        }
368
        }
230
        
369
        
231
        return rgbArray;
370
        return rgbArray;
232
233
    }
371
    }
234
    
372
    
235
    /**
373
    /**
Lines 251-258 Link Here
251
                    float x, float y, float w, float h,
389
                    float x, float y, float w, float h,
252
                    float bboxx, float bboxy, float bboxw, float bboxh,
390
                    float bboxx, float bboxy, float bboxw, float bboxh,
253
                    PSGenerator gen) throws IOException {
391
                    PSGenerator gen) throws IOException {
254
        gen.notifyResourceUsage(PSProcSets.EPS_PROCSET, false);
392
        gen.getResourceTracker().notifyResourceUsageOnPage(PSProcSets.EPS_PROCSET);
255
        gen.writeln("%FOPBeginEPS: " + name);
393
        gen.writeln("%AXGBeginEPS: " + name);
256
        gen.writeln("BeginEPSF");
394
        gen.writeln("BeginEPSF");
257
395
258
        gen.writeln(gen.formatDouble(x) + " " + gen.formatDouble(y) + " translate");
396
        gen.writeln(gen.formatDouble(x) + " " + gen.formatDouble(y) + " translate");
Lines 271-282 Link Here
271
        gen.writeln("newpath");
409
        gen.writeln("newpath");
272
        
410
        
273
        PSResource res = new PSResource(PSResource.TYPE_FILE, name);
411
        PSResource res = new PSResource(PSResource.TYPE_FILE, name);
274
        gen.notifyResourceUsage(res, false);
412
        gen.getResourceTracker().notifyResourceUsageOnPage(res);
275
        gen.writeDSCComment(DSCConstants.BEGIN_DOCUMENT, res.getName());
413
        gen.writeDSCComment(DSCConstants.BEGIN_DOCUMENT, res.getName());
276
        gen.writeByteArr(rawEPS);
414
        gen.writeByteArr(rawEPS);
277
        gen.writeDSCComment(DSCConstants.END_DOCUMENT);
415
        gen.writeDSCComment(DSCConstants.END_DOCUMENT);
278
        gen.writeln("EndEPSF");
416
        gen.writeln("EndEPSF");
279
        gen.writeln("%FOPEndEPS");
417
        gen.writeln("%AXGEndEPS");
280
    }
418
    }
281
419
282
}
420
}
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/ps/PSGenerator.java (-92 / +39 lines)
Lines 27-39 Link Here
27
import java.text.DecimalFormat;
27
import java.text.DecimalFormat;
28
import java.text.DecimalFormatSymbols;
28
import java.text.DecimalFormatSymbols;
29
import java.util.Date;
29
import java.util.Date;
30
import java.util.Iterator;
31
import java.util.Locale;
30
import java.util.Locale;
32
import java.util.Set;
33
import java.util.Stack;
31
import java.util.Stack;
34
32
35
import javax.xml.transform.Source;
33
import javax.xml.transform.Source;
36
34
35
import org.apache.xmlgraphics.ps.dsc.ResourceTracker;
36
37
/**
37
/**
38
 * This class is used to output PostScript code to an OutputStream.
38
 * This class is used to output PostScript code to an OutputStream.
39
 *
39
 *
Lines 41-57 Link Here
41
 */
41
 */
42
public class PSGenerator {
42
public class PSGenerator {
43
43
44
    public static final int DEFAULT_LANGUAGE_LEVEL = 3;
45
    
44
    /** 
46
    /** 
45
     * Indicator for the PostScript interpreter that the value is provided 
47
     * Indicator for the PostScript interpreter that the value is provided 
46
     * later in the document (mostly in the %%Trailer section).
48
     * later in the document (mostly in the %%Trailer section).
49
     * @deprecated Please use DSCConstants.ATEND. This constant was in the wrong place.
47
     */
50
     */
48
    public static final AtendIndicator ATEND = new AtendIndicator() {
51
    public static final Object ATEND = DSCConstants.ATEND;
49
    };
50
52
51
    /** Line feed used by PostScript */
53
    /** Line feed used by PostScript */
52
    public static final char LF = '\n';
54
    public static final char LF = '\n';
53
    
55
    
54
    private OutputStream out;
56
    private OutputStream out;
57
    private int psLevel = DEFAULT_LANGUAGE_LEVEL;
55
    private boolean commentsEnabled = true;
58
    private boolean commentsEnabled = true;
56
    
59
    
57
    private Stack graphicsStateStack = new Stack();
60
    private Stack graphicsStateStack = new Stack();
Lines 62-68 Link Here
62
65
63
    private StringBuffer tempBuffer = new StringBuffer(256);
66
    private StringBuffer tempBuffer = new StringBuffer(256);
64
67
65
    /** @see java.io.FilterOutputStream **/
68
    /**
69
     * Creates a new instance.
70
     * @param out the OutputStream to write the generated PostScript code to
71
     */
66
    public PSGenerator(OutputStream out) {
72
    public PSGenerator(OutputStream out) {
67
        this.out = out;
73
        this.out = out;
68
        this.currentState = new PSState();
74
        this.currentState = new PSState();
Lines 79-92 Link Here
79
85
80
    /**
86
    /**
81
     * Returns the selected PostScript level. 
87
     * Returns the selected PostScript level. 
82
     * (Hardcoded to level 2 for the moment.)
83
     * @return the PostScript level
88
     * @return the PostScript level
84
     */
89
     */
85
    public int getPSLevel() {
90
    public int getPSLevel() {
86
        return 2; 
91
        return this.psLevel; 
87
    }
92
    }
88
    
93
    
89
    /**
94
    /**
95
     * Sets the PostScript level that is used to generate the current document.
96
     * @param level the PostScript level (currently 1, 2 and 3 are known)
97
     */
98
    public void setPSLevel(int level) {
99
        this.psLevel = level;
100
    }
101
    
102
    /**
90
     * Attempts to resolve the given URI. PSGenerator should be subclasses to provide more
103
     * Attempts to resolve the given URI. PSGenerator should be subclasses to provide more
91
     * sophisticated URI resolution.
104
     * sophisticated URI resolution.
92
     * @param uri URI to access
105
     * @param uri URI to access
Lines 238-243 Link Here
238
        return convertStringToDSC(text, false);
251
        return convertStringToDSC(text, false);
239
    }
252
    }
240
253
254
    /**
255
     * Converts a <real> value for use in DSC comments.
256
     * @param value the value to convert
257
     * @return String The resulting String
258
     */
259
    public static final String convertRealToDSC(float value) {
260
        return Float.toString(value);
261
    }
241
262
242
    /**
263
    /**
243
     * Converts text by applying escaping rules established in the DSC specs.
264
     * Converts text by applying escaping rules established in the DSC specs.
Lines 319-326 Link Here
319
                
340
                
320
                if (params[i] instanceof String) {
341
                if (params[i] instanceof String) {
321
                    tempBuffer.append(convertStringToDSC((String)params[i]));
342
                    tempBuffer.append(convertStringToDSC((String)params[i]));
322
                } else if (params[i] instanceof AtendIndicator) {
343
                } else if (params[i] == DSCConstants.ATEND) {
323
                    tempBuffer.append("(atend)");
344
                    tempBuffer.append(DSCConstants.ATEND);
324
                } else if (params[i] instanceof Double) {
345
                } else if (params[i] instanceof Double) {
325
                    tempBuffer.append(df3.format(params[i]));
346
                    tempBuffer.append(df3.format(params[i]));
326
                } else if (params[i] instanceof Number) {
347
                } else if (params[i] instanceof Number) {
Lines 505-600 Link Here
505
        }
526
        }
506
    }
527
    }
507
    
528
    
508
    private Set documentSuppliedResources;
529
    private ResourceTracker resTracker = new ResourceTracker();
509
    private Set documentNeededResources;
510
    private Set pageResources;
511
    
530
    
512
    /**
531
    /**
513
     * Notifies the generator that a new page has been started and that the page resource
532
     * Resturns the ResourceTracker instance associated with this PSGenerator.
514
     * set can be cleared.
533
     * @return the ResourceTracker instance or null if none is assigned
515
     */
534
     */
516
    public void notifyStartNewPage() {
535
    public ResourceTracker getResourceTracker() {
517
        if (pageResources != null) {
536
        return this.resTracker;
518
            pageResources.clear();
519
        }
520
    }
537
    }
521
    
538
    
522
    /**
539
    /**
523
     * Notifies the generator about the usage of a resource on the current page.
540
     * Sets the ResourceTracker instance to be associated with this PSGenerator.
524
     * @param res the resource being used
541
     * @param resTracker the ResourceTracker instance
525
     * @param needed true if this is a needed resource, false for a supplied resource
526
     */
542
     */
527
    public void notifyResourceUsage(PSResource res, boolean needed) {
543
    public void setResourceTracker(ResourceTracker resTracker) {
528
        if (pageResources == null) {
544
        this.resTracker = resTracker;
529
            pageResources = new java.util.HashSet();
530
        }
531
        pageResources.add(res);
532
        if (needed) {
533
            if (documentNeededResources == null) {
534
                documentNeededResources = new java.util.HashSet();
535
            }
536
            documentNeededResources.add(res);
537
        } else {
538
            if (documentSuppliedResources == null) {
539
                documentSuppliedResources = new java.util.HashSet();
540
            }
541
            documentSuppliedResources.add(res);
542
        }
543
    }
545
    }
544
545
    /**
546
     * Indicates whether a particular resource is supplied, rather than needed.
547
     * @param res the resource
548
     * @return true if the resource is registered as being supplied.
549
     */
550
    public boolean isResourceSupplied(PSResource res) {
551
        return documentSuppliedResources.contains(res);
552
    }
553
554
    /**
555
     * Writes a DSC comment for the accumulated used resources, either at page level or
556
     * at document level.
557
     * @param pageLevel true if the DSC comment for the page level should be generated, 
558
     *                  false for the document level (in the trailer)
559
     * @exception IOException In case of an I/O problem
560
     */
561
    public void writeResources(boolean pageLevel) throws IOException {
562
        if (pageLevel) {
563
            writeResourceComment(DSCConstants.PAGE_RESOURCES, pageResources);
564
        } else {
565
            writeResourceComment(DSCConstants.DOCUMENT_NEEDED_RESOURCES, 
566
                    documentNeededResources);
567
            writeResourceComment(DSCConstants.DOCUMENT_SUPPLIED_RESOURCES, 
568
                    documentSuppliedResources);
569
        }
570
    }
571
    
546
    
572
    private void writeResourceComment(String name, Set resources) throws IOException {
573
        if (resources == null || resources.size() == 0) {
574
            return;
575
        }
576
        tempBuffer.setLength(0);
577
        tempBuffer.append("%%");
578
        tempBuffer.append(name);
579
        tempBuffer.append(" ");
580
        boolean first = true;
581
        Iterator i = resources.iterator();
582
        while (i.hasNext()) {
583
            if (!first) {
584
                writeln(tempBuffer.toString());
585
                tempBuffer.setLength(0);
586
                tempBuffer.append("%%+ ");
587
            }
588
            PSResource res = (PSResource)i.next();
589
            tempBuffer.append(res.getResourceSpecification());
590
            first = false;
591
        }
592
        writeln(tempBuffer.toString());
593
    }
594
    
595
    /** Used for the ATEND constant. See there. */
596
    private static interface AtendIndicator {
597
    }
598
599
600
}
547
}
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/ps/dsc/DSCFilter.java (+36 lines)
Line 0 Link Here
1
/*
2
 * Licensed to the Apache Software Foundation (ASF) under one or more
3
 * contributor license agreements.  See the NOTICE file distributed with
4
 * this work for additional information regarding copyright ownership.
5
 * The ASF licenses this file to You under the Apache License, Version 2.0
6
 * (the "License"); you may not use this file except in compliance with
7
 * the License.  You may obtain a copy of the License at
8
 * 
9
 *      http://www.apache.org/licenses/LICENSE-2.0
10
 * 
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
18
/* $Id$ */
19
20
package org.apache.xmlgraphics.ps.dsc;
21
22
import org.apache.xmlgraphics.ps.dsc.events.DSCEvent;
23
24
/**
25
 * Filter interface for DSC events used by the DSC parser.
26
 */
27
public interface DSCFilter {
28
29
    /**
30
     * Indicates whether a particular event is acceptable or if it should be skipped/ignored.
31
     * @param event the DSC event
32
     * @return true if the event should be accepted
33
     */
34
    boolean accept(DSCEvent event);
35
    
36
}
0
  + native
37
  + native
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/ps/dsc/NestedDocumentHandler.java (+45 lines)
Line 0 Link Here
1
/*
2
 * Licensed to the Apache Software Foundation (ASF) under one or more
3
 * contributor license agreements.  See the NOTICE file distributed with
4
 * this work for additional information regarding copyright ownership.
5
 * The ASF licenses this file to You under the Apache License, Version 2.0
6
 * (the "License"); you may not use this file except in compliance with
7
 * the License.  You may obtain a copy of the License at
8
 * 
9
 *      http://www.apache.org/licenses/LICENSE-2.0
10
 * 
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
18
/* $Id$ */
19
20
package org.apache.xmlgraphics.ps.dsc;
21
22
import java.io.IOException;
23
24
import org.apache.xmlgraphics.ps.dsc.events.DSCEvent;
25
26
/**
27
 * Interface that is used to delegate the handling of nested documents (EPS files, data sections)
28
 * in a PostScript document. The implementation receives a parser instance so it can step forward
29
 * until the end of the nested document is reached at which point control is given back to the
30
 * original consumer.
31
 */
32
public interface NestedDocumentHandler {
33
34
    /**
35
     * Handle a DSC event. Implementations may issue additional calls to the DSC parser and may
36
     * modify its state. When returning from the call, state information such as filters should
37
     * be restored.
38
     * @param event the DSC event to handle
39
     * @param parser the DSC parser to work with
40
     * @throws IOException In case of an I/O error
41
     * @throws DSCException In case of a violation of the DSC spec
42
     */
43
    void handle(DSCEvent event, DSCParser parser) throws IOException, DSCException;
44
45
}
0
  + native
46
  + native
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/ps/dsc/tools/PageExtractor.java (+119 lines)
Line 0 Link Here
1
/*
2
 * Licensed to the Apache Software Foundation (ASF) under one or more
3
 * contributor license agreements.  See the NOTICE file distributed with
4
 * this work for additional information regarding copyright ownership.
5
 * The ASF licenses this file to You under the Apache License, Version 2.0
6
 * (the "License"); you may not use this file except in compliance with
7
 * the License.  You may obtain a copy of the License at
8
 * 
9
 *      http://www.apache.org/licenses/LICENSE-2.0
10
 * 
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
18
/* $Id$ */
19
20
package org.apache.xmlgraphics.ps.dsc.tools;
21
22
import java.io.IOException;
23
import java.io.InputStream;
24
import java.io.OutputStream;
25
26
import org.apache.xmlgraphics.ps.DSCConstants;
27
import org.apache.xmlgraphics.ps.PSGenerator;
28
import org.apache.xmlgraphics.ps.dsc.DSCException;
29
import org.apache.xmlgraphics.ps.dsc.DSCFilter;
30
import org.apache.xmlgraphics.ps.dsc.DSCParser;
31
import org.apache.xmlgraphics.ps.dsc.DSCParserConstants;
32
import org.apache.xmlgraphics.ps.dsc.DefaultNestedDocumentHandler;
33
import org.apache.xmlgraphics.ps.dsc.events.DSCComment;
34
import org.apache.xmlgraphics.ps.dsc.events.DSCCommentPage;
35
import org.apache.xmlgraphics.ps.dsc.events.DSCCommentPages;
36
import org.apache.xmlgraphics.ps.dsc.events.DSCEvent;
37
import org.apache.xmlgraphics.ps.dsc.events.DSCHeaderComment;
38
39
/**
40
 * This class can extract a certain range of pages from a DSC-compliant PostScript file.
41
 */
42
public class PageExtractor implements DSCParserConstants {
43
    
44
    /**
45
     * Parses a DSC-compliant file and pipes the content through to the OutputStream omitting
46
     * all pages not within the range.
47
     * @param in the InputStream to parse from 
48
     * @param out the OutputStream to write the modified file to
49
     * @param from the starting page (1-based)
50
     * @param to the last page (inclusive, 1-based)
51
     * @throws IOException In case of an I/O error
52
     * @throws DSCException In case of a violation of the DSC spec
53
     */
54
    public static void extractPages(InputStream in, OutputStream out, int from, int to) 
55
                throws IOException, DSCException {
56
        if (from <= 0) {
57
            throw new IllegalArgumentException("'from' page number must be 1 or higher");
58
        }
59
        if (to < from) {
60
            throw new IllegalArgumentException(
61
                    "'to' page number must be equal or larger than the 'from' page number");
62
        }
63
        
64
        DSCParser parser = new DSCParser(in);
65
        PSGenerator gen = new PSGenerator(out);
66
        parser.setNestedDocumentHandler(new DefaultNestedDocumentHandler(gen));
67
        int pageCount = 0;
68
        
69
        //Skip DSC header
70
        DSCHeaderComment header = DSCTools.checkAndSkipDSC30Header(parser);
71
        header.generate(gen);
72
        //Set number of pages
73
        DSCCommentPages pages = new DSCCommentPages(to - from + 1);
74
        pages.generate(gen);
75
76
        parser.setFilter(new DSCFilter() {
77
            public boolean accept(DSCEvent event) {
78
                if (event.isDSCComment()) {
79
                    //Filter %%Pages which we add manually above
80
                    return !event.asDSCComment().getName().equals(DSCConstants.PAGES);
81
                } else {
82
                    return true;
83
                }
84
            }
85
        });
86
87
        //Skip the prolog and to the first page
88
        DSCComment pageOrTrailer = parser.nextDSCComment(DSCConstants.PAGE, gen);
89
        if (pageOrTrailer == null) {
90
            throw new DSCException("Page expected, but none found");
91
        }
92
        parser.setFilter(null); //Remove filter
93
        
94
        //Process individual pages (and skip as necessary)
95
        while (true) {
96
            DSCCommentPage page = (DSCCommentPage)pageOrTrailer;
97
            boolean validPage = (page.getPagePosition() >= from && page.getPagePosition() <= to);
98
            if (validPage) {
99
                page.setPagePosition(page.getPagePosition() - from + 1);
100
                page.generate(gen);
101
                pageCount++;
102
            }
103
            pageOrTrailer = DSCTools.nextPageOrTrailer(parser, (validPage ? gen : null));
104
            if (pageOrTrailer == null) {
105
                throw new DSCException("File is not DSC-compliant: Unexpected end of file");
106
            } else if (!DSCConstants.PAGE.equals(pageOrTrailer.getName())) {
107
                pageOrTrailer.generate(gen);
108
                break;
109
            }
110
        }
111
        
112
        //Write the rest
113
        while (parser.hasNext()) {
114
            DSCEvent event = parser.nextEvent();
115
            event.generate(gen);
116
        }
117
    }
118
    
119
}
0
  + native
120
  + native
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/ps/dsc/tools/DSCTools.java (+120 lines)
Line 0 Link Here
1
/*
2
 * Licensed to the Apache Software Foundation (ASF) under one or more
3
 * contributor license agreements.  See the NOTICE file distributed with
4
 * this work for additional information regarding copyright ownership.
5
 * The ASF licenses this file to You under the Apache License, Version 2.0
6
 * (the "License"); you may not use this file except in compliance with
7
 * the License.  You may obtain a copy of the License at
8
 * 
9
 *      http://www.apache.org/licenses/LICENSE-2.0
10
 * 
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
18
/* $Id$ */
19
20
package org.apache.xmlgraphics.ps.dsc.tools;
21
22
import java.io.IOException;
23
24
import org.apache.xmlgraphics.ps.DSCConstants;
25
import org.apache.xmlgraphics.ps.PSGenerator;
26
import org.apache.xmlgraphics.ps.dsc.DSCException;
27
import org.apache.xmlgraphics.ps.dsc.DSCParser;
28
import org.apache.xmlgraphics.ps.dsc.DSCParserConstants;
29
import org.apache.xmlgraphics.ps.dsc.events.DSCComment;
30
import org.apache.xmlgraphics.ps.dsc.events.DSCEvent;
31
import org.apache.xmlgraphics.ps.dsc.events.DSCHeaderComment;
32
import org.apache.xmlgraphics.ps.dsc.events.PostScriptComment;
33
34
/**
35
 * Helper methods commonly used when dealing with DSC-compliant PostScript files.
36
 */
37
public class DSCTools implements DSCParserConstants {
38
39
    /**
40
     * Indicates whether the given event ends a header comment section according to the rules in
41
     * DSC 3.0, chapter 4.4.
42
     * @param event the event to check
43
     * @return true if a header comment section would be ended either explicitely or implicitely
44
     *              by the given event
45
     */
46
    public static boolean headerCommentsEndHere(DSCEvent event) {
47
        switch (event.getEventType()) {
48
        case DSC_COMMENT:
49
            DSCComment comment = event.asDSCComment();
50
            return (comment.getName().equals(DSCConstants.END_COMMENTS));
51
        case COMMENT:
52
            String s = ((PostScriptComment)event).getComment();
53
            if (s == null || s.length() == 0) {
54
                return true;
55
            } else {
56
                char c = s.charAt(0);
57
                return ("\n\t ".indexOf(c) >= 0);
58
            }
59
        default:
60
            return true;
61
        }
62
    }
63
64
    /**
65
     * Verifies that the file being parsed is a DSC 3.0 file.
66
     * @param parser the DSC parser
67
     * @return the header comment event
68
     * @throws DSCException In case of a violation of the DSC spec
69
     * @throws IOException In case of an I/O problem
70
     */
71
    public static DSCHeaderComment checkAndSkipDSC30Header(DSCParser parser)
72
                throws DSCException, IOException {
73
        if (!parser.hasNext()) {
74
            throw new DSCException("File has no content");
75
        }
76
        DSCEvent event = parser.nextEvent();
77
        if (event.getEventType() == HEADER_COMMENT) {
78
            DSCHeaderComment header = (DSCHeaderComment)event;
79
            if (!header.isPSAdobe30()) {
80
                throw new DSCException("PostScript file does not start with '" 
81
                        + DSCConstants.PS_ADOBE_30 + "'");
82
            }
83
            return header;
84
        } else {
85
            throw new DSCException("PostScript file does not start with '" 
86
                    + DSCConstants.PS_ADOBE_30 + "'");
87
        }
88
    }
89
    
90
    /**
91
     * Advances the parser to the next page or to the trailer or the end of file comment.
92
     * @param parser the DSC parser
93
     * @param gen the PSGenerator instance to pass the skipped events through to
94
     * @return the DSC comment found (Page, Trailer or EOF)
95
     * @throws IOException In case of an I/O error
96
     * @throws DSCException In case of a violation of the DSC spec
97
     */
98
    public static DSCComment nextPageOrTrailer(DSCParser parser, PSGenerator gen)
99
                throws IOException, DSCException {
100
        while (parser.hasNext()) {
101
            DSCEvent event = parser.nextEvent();
102
            if (event.getEventType() == DSC_COMMENT) {
103
                DSCComment comment = event.asDSCComment();
104
                if (DSCConstants.PAGE.equals(comment.getName())) {
105
                    return comment;
106
                } else if (DSCConstants.TRAILER.equals(comment.getName())) {
107
                    return comment;
108
                }
109
            } else if (event.getEventType() == EOF) {
110
                //The Trailer may be missing
111
                return event.asDSCComment();
112
            }
113
            if (gen != null) {
114
                event.generate(gen); //Pipe through to PSGenerator
115
            }
116
        }
117
        return null;
118
    }
119
120
}
0
  + native
121
  + native
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/ps/dsc/tools/package.html (+23 lines)
Line 0 Link Here
1
<!--
2
  Licensed to the Apache Software Foundation (ASF) under one or more
3
  contributor license agreements.  See the NOTICE file distributed with
4
  this work for additional information regarding copyright ownership.
5
  The ASF licenses this file to You under the Apache License, Version 2.0
6
  (the "License"); you may not use this file except in compliance with
7
  the License.  You may obtain a copy of the License at
8
9
       http://www.apache.org/licenses/LICENSE-2.0
10
11
  Unless required by applicable law or agreed to in writing, software
12
  distributed under the License is distributed on an "AS IS" BASIS,
13
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
  See the License for the specific language governing permissions and
15
  limitations under the License.
16
-->
17
<!-- $Id$ -->
18
<HTML>
19
<TITLE>org.apache.xmlgraphics.ps.dsc.tools Package</TITLE>
20
<BODY>
21
<P>Tools for working with DSC-compliant PostScript files.</P>
22
</BODY>
23
</HTML>
0
  + native
24
  + native
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/ps/dsc/DSCParserConstants.java (+38 lines)
Line 0 Link Here
1
/*
2
 * Licensed to the Apache Software Foundation (ASF) under one or more
3
 * contributor license agreements.  See the NOTICE file distributed with
4
 * this work for additional information regarding copyright ownership.
5
 * The ASF licenses this file to You under the Apache License, Version 2.0
6
 * (the "License"); you may not use this file except in compliance with
7
 * the License.  You may obtain a copy of the License at
8
 * 
9
 *      http://www.apache.org/licenses/LICENSE-2.0
10
 * 
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
18
/* $Id$ */
19
20
package org.apache.xmlgraphics.ps.dsc;
21
22
/**
23
 * Constants the DSC parser uses.
24
 */
25
public interface DSCParserConstants {
26
27
    /** Indicates a header comment (starting with "%!") */
28
    int HEADER_COMMENT = 0;
29
    /** Indicates a DSC comment (starting with "%%") */
30
    int DSC_COMMENT = 1;
31
    /** Indicates a normal PostScript comment (starting with "%") */
32
    int COMMENT = 2;
33
    /** Indicates a normal PostScript line */
34
    int LINE = 3;
35
    /** Indicates the end of the file (equivalent to the "%%EOF" DSC comment) */
36
    int EOF = 4;
37
    
38
}
0
  + native
39
  + native
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/ps/dsc/ResourceTracker.java (+173 lines)
Line 0 Link Here
1
/*
2
 * Licensed to the Apache Software Foundation (ASF) under one or more
3
 * contributor license agreements.  See the NOTICE file distributed with
4
 * this work for additional information regarding copyright ownership.
5
 * The ASF licenses this file to You under the Apache License, Version 2.0
6
 * (the "License"); you may not use this file except in compliance with
7
 * the License.  You may obtain a copy of the License at
8
 * 
9
 *      http://www.apache.org/licenses/LICENSE-2.0
10
 * 
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
18
/* $Id$ */
19
20
package org.apache.xmlgraphics.ps.dsc;
21
22
import java.io.IOException;
23
import java.util.Collection;
24
import java.util.Collections;
25
import java.util.Iterator;
26
import java.util.Set;
27
28
import org.apache.xmlgraphics.ps.PSGenerator;
29
import org.apache.xmlgraphics.ps.PSResource;
30
import org.apache.xmlgraphics.ps.dsc.events.DSCCommentDocumentNeededResources;
31
import org.apache.xmlgraphics.ps.dsc.events.DSCCommentDocumentSuppliedResources;
32
import org.apache.xmlgraphics.ps.dsc.events.DSCCommentPageResources;
33
34
/**
35
 * This class is used to track resources in a DSC-compliant PostScript file. The distinction is
36
 * made between supplied and needed resources. For the details of this distinction, please see
37
 * the DSC specification.
38
 */
39
public class ResourceTracker {
40
41
    private Set documentSuppliedResources;
42
    private Set documentNeededResources;
43
    private Set usedResources;
44
    private Set pageResources;
45
    
46
    /**
47
     * Returns the set of supplied resources.
48
     * @return the set of supplied resources
49
     */
50
    public Set getDocumentSuppliedResources() {
51
        if (documentSuppliedResources != null) {
52
            return Collections.unmodifiableSet(documentSuppliedResources);
53
        } else {
54
            return Collections.EMPTY_SET;
55
        }
56
    }
57
    
58
    /**
59
     * Returns the set of needed resources.
60
     * @return the set of needed resources
61
     */
62
    public Set getDocumentNeededResources() {
63
        if (documentNeededResources != null) {
64
            return Collections.unmodifiableSet(documentNeededResources);
65
        } else {
66
            return Collections.EMPTY_SET;
67
        }
68
    }
69
    
70
    /**
71
     * Notifies the resource tracker that a new page has been started and that the page resource
72
     * set can be cleared.
73
     */
74
    public void notifyStartNewPage() {
75
        if (pageResources != null) {
76
            pageResources.clear();
77
        }
78
    }
79
    
80
    /**
81
     * Registers a supplied resource. If the same resources is already in the set of needed
82
     * resources, it is removed there.
83
     * @param res the resource
84
     */
85
    public void registerSuppliedResource(PSResource res) {
86
        if (documentSuppliedResources == null) {
87
            documentSuppliedResources = new java.util.HashSet();
88
        }
89
        documentSuppliedResources.add(res);
90
        if (documentNeededResources != null) {
91
            documentNeededResources.remove(res);
92
        }
93
    }
94
    
95
    /**
96
     * Registers a needed resource. If the same resources is already in the set of supplied
97
     * resources, it is ignored, i.e. it is assumed to be supplied.
98
     * @param res the resource
99
     */
100
    public void registerNeededResource(PSResource res) {
101
        if (documentNeededResources == null) {
102
            documentNeededResources = new java.util.HashSet();
103
        }
104
        if (!documentSuppliedResources.contains(res)) {
105
            documentNeededResources.add(res);
106
        }
107
    }
108
    
109
    /**
110
     * Notifies the resource tracker about the usage of a resource on the current page.
111
     * @param res the resource being used
112
     */
113
    public void notifyResourceUsageOnPage(PSResource res) {
114
        if (pageResources == null) {
115
            pageResources = new java.util.HashSet();
116
        }
117
        pageResources.add(res);
118
    }
119
120
    /**
121
     * Notifies the resource tracker about the usage of resources on the current page.
122
     * @param resources the resources being used
123
     */
124
    public void notifyResourceUsageOnPage(Collection resources) {
125
        if (pageResources == null) {
126
            pageResources = new java.util.HashSet();
127
        }
128
        pageResources.addAll(resources);
129
    }
130
131
    /**
132
     * Indicates whether a particular resource is supplied, rather than needed.
133
     * @param res the resource
134
     * @return true if the resource is registered as being supplied.
135
     */
136
    public boolean isResourceSupplied(PSResource res) {
137
        return (documentSuppliedResources != null) && documentSuppliedResources.contains(res);
138
    }
139
140
    /**
141
     * Writes a DSC comment for the accumulated used resources, either at page level or
142
     * at document level.
143
     * @param pageLevel true if the DSC comment for the page level should be generated, 
144
     *                  false for the document level (in the trailer)
145
     * @param gen the PSGenerator to write the DSC comments with
146
     * @exception IOException In case of an I/O problem
147
     */
148
    public void writeResources(boolean pageLevel, PSGenerator gen) throws IOException {
149
        if (pageLevel) {
150
            new DSCCommentPageResources(pageResources).generate(gen);
151
            if (usedResources == null) {
152
                usedResources = new java.util.HashSet();
153
            }
154
            usedResources.addAll(pageResources);
155
        } else {
156
            if (usedResources != null) {
157
                Iterator iter = usedResources.iterator();
158
                while (iter.hasNext()) {
159
                    PSResource res = (PSResource)iter.next();
160
                    if (documentSuppliedResources == null 
161
                            || !documentSuppliedResources.contains(res)) {
162
                        registerNeededResource(res);
163
                    }
164
                }
165
            }
166
            new DSCCommentDocumentNeededResources(documentNeededResources).generate(gen);
167
            new DSCCommentDocumentSuppliedResources(documentSuppliedResources).generate(gen);
168
        }
169
    }
170
    
171
    
172
    
173
}
0
  + native
174
  + native
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/ps/dsc/events/AbstractEvent.java (+69 lines)
Line 0 Link Here
1
/*
2
 * Licensed to the Apache Software Foundation (ASF) under one or more
3
 * contributor license agreements.  See the NOTICE file distributed with
4
 * this work for additional information regarding copyright ownership.
5
 * The ASF licenses this file to You under the Apache License, Version 2.0
6
 * (the "License"); you may not use this file except in compliance with
7
 * the License.  You may obtain a copy of the License at
8
 * 
9
 *      http://www.apache.org/licenses/LICENSE-2.0
10
 * 
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
18
/* $Id$ */
19
20
package org.apache.xmlgraphics.ps.dsc.events;
21
22
/**
23
 * Abstract base class for DSC events.
24
 */
25
public abstract class AbstractEvent implements DSCEvent {
26
27
    /**
28
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCEvent#isComment()
29
     */
30
    public boolean isComment() {
31
        return false;
32
    }
33
34
    /**
35
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCEvent#isDSCComment()
36
     */
37
    public boolean isDSCComment() {
38
        return false;
39
    }
40
41
    /**
42
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCEvent#isHeaderComment()
43
     */
44
    public boolean isHeaderComment() {
45
        return false;
46
    }
47
48
    /**
49
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCEvent#isLine()
50
     */
51
    public boolean isLine() {
52
        return false;
53
    }
54
55
    /**
56
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCEvent#asDSCComment()
57
     */
58
    public DSCComment asDSCComment() {
59
        throw new ClassCastException(this.getClass().getName());
60
    }
61
62
    /**
63
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCEvent#asLine()
64
     */
65
    public PostScriptLine asLine() {
66
        throw new ClassCastException(this.getClass().getName());
67
    }
68
69
}
0
  + native
70
  + native
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/ps/dsc/events/DSCHeaderComment.java (+80 lines)
Line 0 Link Here
1
/*
2
 * Licensed to the Apache Software Foundation (ASF) under one or more
3
 * contributor license agreements.  See the NOTICE file distributed with
4
 * this work for additional information regarding copyright ownership.
5
 * The ASF licenses this file to You under the Apache License, Version 2.0
6
 * (the "License"); you may not use this file except in compliance with
7
 * the License.  You may obtain a copy of the License at
8
 * 
9
 *      http://www.apache.org/licenses/LICENSE-2.0
10
 * 
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
18
/* $Id$ */
19
20
package org.apache.xmlgraphics.ps.dsc.events;
21
22
import java.io.IOException;
23
24
import org.apache.xmlgraphics.ps.DSCConstants;
25
import org.apache.xmlgraphics.ps.PSGenerator;
26
27
/**
28
 * Represents a DSC header comment (beginning with "%!).
29
 */
30
public class DSCHeaderComment extends AbstractEvent {
31
32
    private String comment;
33
    
34
    /**
35
     * Creates a new instance.
36
     * @param comment the comment
37
     */
38
    public DSCHeaderComment(String comment) {
39
        this.comment = comment;
40
    }
41
    
42
    /**
43
     * Returns the comment.
44
     * @return the comment
45
     */
46
    public String getComment() {
47
        return this.comment;
48
    }
49
    
50
    /**
51
     * Indicates whether the file started by this comments is DSC 3.0 compliant.
52
     * @return true if the file is DSC 3.0 compliant.
53
     */
54
    public boolean isPSAdobe30() {
55
        return getComment().startsWith(DSCConstants.PS_ADOBE_30.substring(2));
56
    }
57
    
58
    /**
59
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCEvent#generate(
60
     *              org.apache.xmlgraphics.ps.PSGenerator)
61
     */
62
    public void generate(PSGenerator gen) throws IOException {
63
        gen.writeln("%!" + getComment());
64
    }
65
66
    /**
67
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCEvent#getEventType()
68
     */
69
    public int getEventType() {
70
        return HEADER_COMMENT;
71
    }
72
73
    /**
74
     * @see org.apache.xmlgraphics.ps.dsc.events.AbstractEvent#isHeaderComment()
75
     */
76
    public boolean isHeaderComment() {
77
        return true;
78
    }
79
80
}
0
  + native
81
  + native
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/ps/dsc/events/DSCCommentEndOfFile.java (+67 lines)
Line 0 Link Here
1
/*
2
 * Licensed to the Apache Software Foundation (ASF) under one or more
3
 * contributor license agreements.  See the NOTICE file distributed with
4
 * this work for additional information regarding copyright ownership.
5
 * The ASF licenses this file to You under the Apache License, Version 2.0
6
 * (the "License"); you may not use this file except in compliance with
7
 * the License.  You may obtain a copy of the License at
8
 * 
9
 *      http://www.apache.org/licenses/LICENSE-2.0
10
 * 
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
18
/* $Id$ */
19
20
package org.apache.xmlgraphics.ps.dsc.events;
21
22
import java.io.IOException;
23
24
import org.apache.xmlgraphics.ps.DSCConstants;
25
import org.apache.xmlgraphics.ps.PSGenerator;
26
27
/**
28
 * Represents a %%EOF DSC comment.
29
 */
30
public class DSCCommentEndOfFile extends AbstractDSCComment {
31
32
    /**
33
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCComment#getName()
34
     */
35
    public String getName() {
36
        return DSCConstants.EOF;
37
    }
38
39
    /**
40
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCComment#hasValues()
41
     */
42
    public boolean hasValues() {
43
        return false;
44
    }
45
46
    /**
47
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCComment#parseValue(java.lang.String)
48
     */
49
    public void parseValue(String value) {
50
        //nop
51
    }
52
53
    /**
54
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCEvent#generate(org.apache.xmlgraphics.ps.PSGenerator)
55
     */
56
    public void generate(PSGenerator gen) throws IOException {
57
        gen.writeDSCComment(getName());
58
    }
59
60
    /**
61
     * @see org.apache.xmlgraphics.ps.dsc.events.AbstractDSCComment#getEventType()
62
     */
63
    public int getEventType() {
64
        return EOF;
65
    }
66
    
67
}
0
  + native
68
  + native
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/ps/dsc/events/DSCCommentBeginResource.java (+141 lines)
Line 0 Link Here
1
/*
2
 * Licensed to the Apache Software Foundation (ASF) under one or more
3
 * contributor license agreements.  See the NOTICE file distributed with
4
 * this work for additional information regarding copyright ownership.
5
 * The ASF licenses this file to You under the Apache License, Version 2.0
6
 * (the "License"); you may not use this file except in compliance with
7
 * the License.  You may obtain a copy of the License at
8
 * 
9
 *      http://www.apache.org/licenses/LICENSE-2.0
10
 * 
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
18
/* $Id$ */
19
20
package org.apache.xmlgraphics.ps.dsc.events;
21
22
import java.io.IOException;
23
import java.util.Iterator;
24
import java.util.List;
25
26
import org.apache.xmlgraphics.ps.DSCConstants;
27
import org.apache.xmlgraphics.ps.PSGenerator;
28
import org.apache.xmlgraphics.ps.PSProcSet;
29
import org.apache.xmlgraphics.ps.PSResource;
30
31
/**
32
 * Represents a %BeginResource DSC comment.
33
 */
34
public class DSCCommentBeginResource extends AbstractDSCComment {
35
36
    private PSResource resource;
37
    private Integer min;
38
    private Integer max;
39
    
40
    /**
41
     * Creates a new instance
42
     */
43
    public DSCCommentBeginResource() {
44
    }
45
46
    /**
47
     * Creates a new instance for a given PSResource instance
48
     * @param resource the resource
49
     */
50
    public DSCCommentBeginResource(PSResource resource) {
51
        this.resource = resource;
52
    }
53
    
54
    /**
55
     * Creates a new instance for a given PSResource instance
56
     * @param resource the resource
57
     * @param min Minimum VM used by the resource
58
     * @param max Maximum VM used by the resource
59
     */
60
    public DSCCommentBeginResource(PSResource resource, int min, int max) {
61
        this.resource = resource;
62
        this.min = new Integer(min);
63
        this.max = new Integer(max);
64
    }
65
    
66
    /**
67
     * Returns the associated PSResource.
68
     * @return the resource
69
     */
70
    public PSResource getResource() {
71
        return this.resource;
72
    }
73
    
74
    /**
75
     * Returns the minimum VM used by the resource.
76
     * @return the minimum VM used by the resource
77
     */
78
    public Integer getMin() {
79
        return this.min;
80
    }
81
    
82
    /**
83
     * Returns the maximum VM used by the resource.
84
     * @return the maximum VM used by the resource
85
     */
86
    public Integer getMax() {
87
        return this.max;
88
    }
89
90
    /**
91
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCComment#getName()
92
     */
93
    public String getName() {
94
        return DSCConstants.BEGIN_RESOURCE;
95
    }
96
97
    /**
98
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCComment#hasValues()
99
     */
100
    public boolean hasValues() {
101
        return true;
102
    }
103
104
    /**
105
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCComment#parseValue(java.lang.String)
106
     */
107
    public void parseValue(String value) {
108
        List params = splitParams(value);
109
        Iterator iter = params.iterator();
110
        String name = (String)iter.next();
111
        if (PSResource.TYPE_FONT.equals(name)) {
112
            String fontname = (String)iter.next();
113
            this.resource = new PSResource(name, fontname);
114
        } else if (PSResource.TYPE_PROCSET.equals(name)) {
115
            String procname = (String)iter.next();
116
            String version = (String)iter.next();
117
            String revision = (String)iter.next();
118
            this.resource = new PSProcSet(procname, 
119
                    Float.parseFloat(version), Integer.parseInt(revision));
120
        } else if (PSResource.TYPE_FILE.equals(name)) {
121
            String filename = (String)iter.next();
122
            this.resource = new PSResource(name, filename);
123
        } else {
124
            throw new IllegalArgumentException("Invalid resource type: " + name);
125
        }
126
    }
127
    
128
    /**
129
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCEvent#generate(
130
     *          org.apache.xmlgraphics.ps.PSGenerator)
131
     */
132
    public void generate(PSGenerator gen) throws IOException {
133
        if (getMin() != null) {
134
            Object[] params = new Object[] {getResource(), getMin(), getMax()};
135
            gen.writeDSCComment(getName(), params);
136
        } else {
137
            gen.writeDSCComment(getName(), getResource());
138
        }
139
    }
140
141
}
0
  + native
142
  + native
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/ps/dsc/events/DSCEvent.java (+84 lines)
Line 0 Link Here
1
/*
2
 * Licensed to the Apache Software Foundation (ASF) under one or more
3
 * contributor license agreements.  See the NOTICE file distributed with
4
 * this work for additional information regarding copyright ownership.
5
 * The ASF licenses this file to You under the Apache License, Version 2.0
6
 * (the "License"); you may not use this file except in compliance with
7
 * the License.  You may obtain a copy of the License at
8
 * 
9
 *      http://www.apache.org/licenses/LICENSE-2.0
10
 * 
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
18
/* $Id$ */
19
20
package org.apache.xmlgraphics.ps.dsc.events;
21
22
import java.io.IOException;
23
24
import org.apache.xmlgraphics.ps.PSGenerator;
25
import org.apache.xmlgraphics.ps.dsc.DSCParserConstants;
26
27
/**
28
 * Interface representing a DSC event. A DSC event can be a DSC comment, a PostScript comment
29
 * or a line of PostScript code.
30
 */
31
public interface DSCEvent extends DSCParserConstants {
32
33
    /**
34
     * Returns the event type.
35
     * @return the event type (see {@link DSCParserConstants})
36
     */
37
    int getEventType();
38
39
    /**
40
     * Casts this instance to a DSCComment if possible.
41
     * @return this event as a DSCComment
42
     * @throws ClassCastException if the event is no DSCComment
43
     */
44
    DSCComment asDSCComment();
45
    
46
    /**
47
     * Casts this instance to a PostScriptLine if possible.
48
     * @return this event as a PostScriptLine
49
     * @throws ClassCastException if the event is no PostScriptLine
50
     */
51
    PostScriptLine asLine();
52
    
53
    /**
54
     * Indicates whether the instance is a DSC comment.
55
     * @return true if the instance is a DSC comment
56
     */
57
    boolean isDSCComment();
58
    
59
    /**
60
     * Indicates whether the instance is a PostScript comment.
61
     * @return true if the instance is a PostScript comment
62
     */
63
    boolean isComment();
64
    
65
    /**
66
     * Indicates whether the instance is a header comment.
67
     * @return true if the instance is a header comment
68
     */
69
    boolean isHeaderComment();
70
    
71
    /**
72
     * Indicates whether the instance is a PostScript line.
73
     * @return true if the instance is a PostScript line
74
     */
75
    boolean isLine();
76
    
77
    /**
78
     * Writes the event to the given PSGenerator.
79
     * @param gen the PSGenerator to write to
80
     * @throws IOException In case of an I/O error
81
     */
82
    void generate(PSGenerator gen) throws IOException;
83
    
84
}
0
  + native
85
  + native
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/ps/dsc/events/AbstractResourcesDSCComment.java (+171 lines)
Line 0 Link Here
1
/*
2
 * Licensed to the Apache Software Foundation (ASF) under one or more
3
 * contributor license agreements.  See the NOTICE file distributed with
4
 * this work for additional information regarding copyright ownership.
5
 * The ASF licenses this file to You under the Apache License, Version 2.0
6
 * (the "License"); you may not use this file except in compliance with
7
 * the License.  You may obtain a copy of the License at
8
 * 
9
 *      http://www.apache.org/licenses/LICENSE-2.0
10
 * 
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
18
/* $Id$ */
19
20
package org.apache.xmlgraphics.ps.dsc.events;
21
22
import java.io.IOException;
23
import java.util.Collection;
24
import java.util.Collections;
25
import java.util.Iterator;
26
import java.util.List;
27
import java.util.Set;
28
29
import org.apache.xmlgraphics.ps.PSGenerator;
30
import org.apache.xmlgraphics.ps.PSProcSet;
31
import org.apache.xmlgraphics.ps.PSResource;
32
33
/**
34
 * Abstract base class for Resource DSC comments (DocumentNeededResources, 
35
 * DocumentSuppliedResources and PageResources).
36
 */
37
public abstract class AbstractResourcesDSCComment extends AbstractDSCComment {
38
39
    private Set resources;
40
    
41
    /**
42
     * Creates a new instance.
43
     */
44
    public AbstractResourcesDSCComment() {
45
        super();
46
    }
47
    
48
    /**
49
     * Creates a new instance.
50
     * @param resources a Collection of PSResource instances
51
     */
52
    public AbstractResourcesDSCComment(Collection resources) {
53
        addResources(resources);
54
    }
55
    
56
    /**
57
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCComment#hasValues()
58
     */
59
    public boolean hasValues() {
60
        return true;
61
    }
62
63
    /**
64
     * Adds a new resource.
65
     * @param res the resource
66
     */
67
    public void addResource(PSResource res) {
68
        if (this.resources == null) {
69
            this.resources = new java.util.HashSet();
70
        }
71
        this.resources.add(res);
72
    }
73
    
74
    /**
75
     * Adds a collection of resources.
76
     * @param resources a Collection of PSResource instances. 
77
     */
78
    public void addResources(Collection resources) {
79
        if (resources != null) {
80
            if (this.resources == null) {
81
                this.resources = new java.util.HashSet();
82
            }
83
            this.resources.addAll(resources);
84
        }
85
    }
86
    
87
    /**
88
     * Returns the set of resources associated with this DSC comment.
89
     * @return the set of resources
90
     */
91
    public Set getResources() {
92
        return Collections.unmodifiableSet(this.resources);
93
    }
94
    
95
    /**
96
     * Defines the known resource types (font, procset, file, pattern etc.).
97
     */
98
    protected static final Set RESOURCE_TYPES = new java.util.HashSet();
99
    
100
    static {
101
        RESOURCE_TYPES.add(PSResource.TYPE_FONT);
102
        RESOURCE_TYPES.add(PSResource.TYPE_PROCSET);
103
        RESOURCE_TYPES.add(PSResource.TYPE_FILE);
104
        RESOURCE_TYPES.add(PSResource.TYPE_PATTERN);
105
        RESOURCE_TYPES.add(PSResource.TYPE_FORM);
106
        RESOURCE_TYPES.add(PSResource.TYPE_ENCODING);
107
    }
108
    
109
    /**
110
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCComment#parseValue(java.lang.String)
111
     */
112
    public void parseValue(String value) {
113
        List params = splitParams(value);
114
        String currentResourceType = null;
115
        Iterator iter = params.iterator();
116
        while (iter.hasNext()) {
117
            String name = (String)iter.next();
118
            if (RESOURCE_TYPES.contains(name)) {
119
                currentResourceType = name;
120
            }
121
            if (currentResourceType == null) {
122
                throw new IllegalArgumentException(
123
                        "<resources> must begin with a resource type. Found: " + name);
124
            }
125
            if (PSResource.TYPE_FONT.equals(currentResourceType)) {
126
                String fontname = (String)iter.next();
127
                addResource(new PSResource(name, fontname));
128
            } else if (PSResource.TYPE_FORM.equals(currentResourceType)) {
129
                String formname = (String)iter.next();
130
                addResource(new PSResource(name, formname));
131
            } else if (PSResource.TYPE_PROCSET.equals(currentResourceType)) {
132
                String procname = (String)iter.next();
133
                String version = (String)iter.next();
134
                String revision = (String)iter.next();
135
                addResource(new PSProcSet(procname, 
136
                        Float.parseFloat(version), Integer.parseInt(revision)));
137
            } else if (PSResource.TYPE_FILE.equals(currentResourceType)) {
138
                String filename = (String)iter.next();
139
                addResource(new PSResource(name, filename));
140
            } else {
141
                throw new IllegalArgumentException("Invalid resource type: " + currentResourceType);
142
            }
143
        }
144
    }
145
146
    /**
147
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCEvent#generate(
148
     *          org.apache.xmlgraphics.ps.PSGenerator)
149
     */
150
    public void generate(PSGenerator gen) throws IOException {
151
        if (resources == null || resources.size() == 0) {
152
            return;
153
        }
154
        StringBuffer sb = new StringBuffer();
155
        sb.append("%%").append(getName()).append(": ");
156
        boolean first = true;
157
        Iterator i = resources.iterator();
158
        while (i.hasNext()) {
159
            if (!first) {
160
                gen.writeln(sb.toString());
161
                sb.setLength(0);
162
                sb.append("%%+ ");
163
            }
164
            PSResource res = (PSResource)i.next();
165
            sb.append(res.getResourceSpecification());
166
            first = false;
167
        }
168
        gen.writeln(sb.toString());
169
    }
170
171
}
0
  + native
172
  + native
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/ps/dsc/events/DSCCommentPages.java (+96 lines)
Line 0 Link Here
1
/*
2
 * Licensed to the Apache Software Foundation (ASF) under one or more
3
 * contributor license agreements.  See the NOTICE file distributed with
4
 * this work for additional information regarding copyright ownership.
5
 * The ASF licenses this file to You under the Apache License, Version 2.0
6
 * (the "License"); you may not use this file except in compliance with
7
 * the License.  You may obtain a copy of the License at
8
 * 
9
 *      http://www.apache.org/licenses/LICENSE-2.0
10
 * 
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
18
/* $Id$ */
19
20
package org.apache.xmlgraphics.ps.dsc.events;
21
22
import java.io.IOException;
23
24
import org.apache.xmlgraphics.ps.DSCConstants;
25
import org.apache.xmlgraphics.ps.PSGenerator;
26
27
/**
28
 * Represents the %%Pages DSC comment.
29
 */
30
public class DSCCommentPages extends AbstractDSCComment {
31
32
    private int pageCount = -1;
33
    
34
    /**
35
     * Creates a new instance.
36
     */
37
    public DSCCommentPages() {
38
    }
39
40
    /**
41
     * Creates a new instance.
42
     * @param pageCount the number of pages
43
     */
44
    public DSCCommentPages(int pageCount) {
45
        this.pageCount = pageCount;
46
    }
47
    
48
    /**
49
     * Returns the page count.
50
     * @return the page count
51
     */
52
    public int getPageCount() {
53
        return this.pageCount;
54
    }
55
    
56
    /**
57
     * Sets the page count.
58
     * @param count the new page count
59
     */
60
    public void setPageCount(int count) {
61
        this.pageCount = count;
62
    }
63
64
    /**
65
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCComment#getName()
66
     */
67
    public String getName() {
68
        return DSCConstants.PAGES;
69
    }
70
71
    /**
72
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCComment#hasValues()
73
     */
74
    public boolean hasValues() {
75
        return true;
76
    }
77
78
    /**
79
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCComment#parseValue(java.lang.String)
80
     */
81
    public void parseValue(String value) {
82
        this.pageCount = Integer.parseInt(value);
83
    }
84
    
85
    /**
86
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCEvent#generate(org.apache.xmlgraphics.ps.PSGenerator)
87
     */
88
    public void generate(PSGenerator gen) throws IOException {
89
        if (getPageCount() > 0) {
90
            gen.writeDSCComment(getName(), new Integer(getPageCount()));
91
        } else {
92
            gen.writeDSCComment(getName(), DSCConstants.ATEND);
93
        }
94
    }
95
96
}
0
  + native
97
  + native
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/ps/dsc/events/package.html (+23 lines)
Line 0 Link Here
1
<!--
2
  Licensed to the Apache Software Foundation (ASF) under one or more
3
  contributor license agreements.  See the NOTICE file distributed with
4
  this work for additional information regarding copyright ownership.
5
  The ASF licenses this file to You under the Apache License, Version 2.0
6
  (the "License"); you may not use this file except in compliance with
7
  the License.  You may obtain a copy of the License at
8
9
       http://www.apache.org/licenses/LICENSE-2.0
10
11
  Unless required by applicable law or agreed to in writing, software
12
  distributed under the License is distributed on an "AS IS" BASIS,
13
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
  See the License for the specific language governing permissions and
15
  limitations under the License.
16
-->
17
<!-- $Id$ -->
18
<HTML>
19
<TITLE>org.apache.xmlgraphics.ps.dsc.events Package</TITLE>
20
<BODY>
21
<P>Event classes used by the DSC parser.</P>
22
</BODY>
23
</HTML>
0
  + native
24
  + native
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/ps/dsc/events/AbstractDSCComment.java (+157 lines)
Line 0 Link Here
1
/*
2
 * Licensed to the Apache Software Foundation (ASF) under one or more
3
 * contributor license agreements.  See the NOTICE file distributed with
4
 * this work for additional information regarding copyright ownership.
5
 * The ASF licenses this file to You under the Apache License, Version 2.0
6
 * (the "License"); you may not use this file except in compliance with
7
 * the License.  You may obtain a copy of the License at
8
 * 
9
 *      http://www.apache.org/licenses/LICENSE-2.0
10
 * 
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
18
/* $Id$ */
19
20
package org.apache.xmlgraphics.ps.dsc.events;
21
22
import java.util.List;
23
24
/**
25
 * Abstract base class for DSC comments.
26
 */
27
public abstract class AbstractDSCComment extends AbstractEvent implements DSCComment {
28
29
    private final boolean isWhitespace(char c) {
30
        return c == ' ' || c == '\t';
31
    }
32
    
33
    private int parseNextParam(String value, int pos, List lst) {
34
        int startPos = pos;
35
        pos++;
36
        while (pos < value.length() && !isWhitespace(value.charAt(pos))) {
37
            pos++;
38
        }
39
        String param = value.substring(startPos, pos);
40
        lst.add(param);
41
        return pos;
42
    }
43
    
44
    private int parseNextParentheseString(String value, int pos, List lst) {
45
        int nestLevel = 1;
46
        pos++;
47
        StringBuffer sb = new StringBuffer();
48
        while (pos < value.length() && nestLevel > 0) {
49
            final char c = value.charAt(pos);
50
            switch (c) {
51
            case '(':
52
                nestLevel++;
53
                if (nestLevel > 1) {
54
                    sb.append(c);
55
                }
56
                break;
57
            case ')':
58
                if (nestLevel > 1) {
59
                    sb.append(c);
60
                }
61
                nestLevel--;
62
                break;
63
            case '\\':
64
                pos++;
65
                char cnext = value.charAt(pos);
66
                switch (cnext) {
67
                case '\\':
68
                    sb.append(cnext);
69
                    break;
70
                case 'n':
71
                    sb.append('\n');
72
                    break;
73
                case 'r':
74
                    sb.append('\r');
75
                    break;
76
                case 't':
77
                    sb.append('\t');
78
                    break;
79
                case 'b':
80
                    sb.append('\b');
81
                    break;
82
                case 'f':
83
                    sb.append('\f');
84
                    break;
85
                case '(':
86
                    sb.append('(');
87
                    break;
88
                case ')':
89
                    sb.append(')');
90
                    break;
91
                default:
92
                    int code = Integer.parseInt(value.substring(pos, pos + 3), 8);
93
                    sb.append((char)code);
94
                    pos += 2;
95
                }
96
                break;
97
            default:
98
                sb.append(c);
99
            }
100
            pos++;
101
        }
102
        lst.add(sb.toString());
103
        pos++;
104
        return pos;
105
    }
106
    
107
    /**
108
     * Splits the params of the DSC comment value in to a List.
109
     * @param value the DSC comment value
110
     * @return the List of values
111
     */
112
    protected List splitParams(String value) {
113
        List lst = new java.util.ArrayList();
114
        int pos = 0;
115
        value = value.trim();
116
        while (pos < value.length()) {
117
            if (isWhitespace(value.charAt(pos))) {
118
                pos++;
119
                continue;
120
            }
121
            if (value.charAt(pos) == '(') {
122
                pos = parseNextParentheseString(value, pos, lst);
123
            } else {
124
                pos = parseNextParam(value, pos, lst);
125
            }
126
        }
127
        return lst;
128
    }
129
    
130
    /**
131
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCComment#isAtend()
132
     */
133
    public boolean isAtend() {
134
        return false;
135
    }
136
    
137
    /**
138
     * @see org.apache.xmlgraphics.ps.dsc.events.AbstractEvent#asDSCComment()
139
     */
140
    public DSCComment asDSCComment() {
141
        return this;
142
    }
143
144
    /**
145
     * @see org.apache.xmlgraphics.ps.dsc.events.AbstractEvent#isDSCComment()
146
     */
147
    public boolean isDSCComment() {
148
        return true;
149
    }
150
151
    /**
152
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCEvent#getEventType()
153
     */
154
    public int getEventType() {
155
        return DSC_COMMENT;
156
    }
157
}
0
  + native
158
  + native
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/ps/dsc/events/PostScriptLine.java (+77 lines)
Line 0 Link Here
1
/*
2
 * Licensed to the Apache Software Foundation (ASF) under one or more
3
 * contributor license agreements.  See the NOTICE file distributed with
4
 * this work for additional information regarding copyright ownership.
5
 * The ASF licenses this file to You under the Apache License, Version 2.0
6
 * (the "License"); you may not use this file except in compliance with
7
 * the License.  You may obtain a copy of the License at
8
 * 
9
 *      http://www.apache.org/licenses/LICENSE-2.0
10
 * 
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
18
/* $Id$ */
19
20
package org.apache.xmlgraphics.ps.dsc.events;
21
22
import java.io.IOException;
23
24
import org.apache.xmlgraphics.ps.PSGenerator;
25
26
/**
27
 * Represents a line of PostScript code.
28
 */
29
public class PostScriptLine extends AbstractEvent {
30
31
    private String line;
32
    
33
    /**
34
     * Creates a new instance.
35
     * @param line the code line
36
     */
37
    public PostScriptLine(String line) {
38
        this.line = line;
39
    }
40
    
41
    /**
42
     * Returns the code line.
43
     * @return the code line
44
     */
45
    public String getLine() {
46
        return this.line;
47
    }
48
    
49
    /**
50
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCEvent#generate(org.apache.xmlgraphics.ps.PSGenerator)
51
     */
52
    public void generate(PSGenerator gen) throws IOException {
53
        gen.writeln(getLine());
54
    }
55
56
    /**
57
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCEvent#getEventType()
58
     */
59
    public int getEventType() {
60
        return LINE;
61
    }
62
63
    /**
64
     * @see org.apache.xmlgraphics.ps.dsc.events.AbstractEvent#asLine()
65
     */
66
    public PostScriptLine asLine() {
67
        return this;
68
    }
69
    
70
    /**
71
     * @see org.apache.xmlgraphics.ps.dsc.events.AbstractEvent#isLine()
72
     */
73
    public boolean isLine() {
74
        return true;
75
    }
76
77
}
0
  + native
78
  + native
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/ps/dsc/events/DSCCommentPageResources.java (+53 lines)
Line 0 Link Here
1
/*
2
 * Licensed to the Apache Software Foundation (ASF) under one or more
3
 * contributor license agreements.  See the NOTICE file distributed with
4
 * this work for additional information regarding copyright ownership.
5
 * The ASF licenses this file to You under the Apache License, Version 2.0
6
 * (the "License"); you may not use this file except in compliance with
7
 * the License.  You may obtain a copy of the License at
8
 * 
9
 *      http://www.apache.org/licenses/LICENSE-2.0
10
 * 
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
18
/* $Id$ */
19
20
package org.apache.xmlgraphics.ps.dsc.events;
21
22
import java.util.Collection;
23
24
import org.apache.xmlgraphics.ps.DSCConstants;
25
26
/**
27
 * Represents a %%PageResources DSC comment.
28
 */
29
public class DSCCommentPageResources extends AbstractResourcesDSCComment {
30
31
    /**
32
     * Creates a new instance.
33
     */
34
    public DSCCommentPageResources() {
35
        super();
36
    }
37
    
38
    /**
39
     * Creates a new instance.
40
     * @param resources a Collection of PSResource instances
41
     */
42
    public DSCCommentPageResources(Collection resources) {
43
        super(resources);
44
    }
45
    
46
    /**
47
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCComment#getName()
48
     */
49
    public String getName() {
50
        return DSCConstants.PAGE_RESOURCES;
51
    }
52
53
}
0
  + native
54
  + native
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/ps/dsc/events/DSCAtend.java (+88 lines)
Line 0 Link Here
1
/*
2
 * Licensed to the Apache Software Foundation (ASF) under one or more
3
 * contributor license agreements.  See the NOTICE file distributed with
4
 * this work for additional information regarding copyright ownership.
5
 * The ASF licenses this file to You under the Apache License, Version 2.0
6
 * (the "License"); you may not use this file except in compliance with
7
 * the License.  You may obtain a copy of the License at
8
 * 
9
 *      http://www.apache.org/licenses/LICENSE-2.0
10
 * 
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
18
/* $Id$ */
19
20
package org.apache.xmlgraphics.ps.dsc.events;
21
22
import java.io.IOException;
23
24
import org.apache.xmlgraphics.ps.DSCConstants;
25
import org.apache.xmlgraphics.ps.PSGenerator;
26
import org.apache.xmlgraphics.ps.dsc.DSCCommentFactory;
27
28
/**
29
 * This class represents a DSC comment with an "(ATEND)" value.
30
 */
31
public class DSCAtend extends AbstractDSCComment {
32
33
    private String name;
34
    
35
    /**
36
     * Creates a new instance
37
     * @param name the name of the DSC comment (without the "%%" prefix)
38
     */
39
    public DSCAtend(String name) {
40
        this.name = name;
41
    }
42
43
    /**
44
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCComment#getName()
45
     */
46
    public String getName() {
47
        return this.name;
48
    }
49
50
    /**
51
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCComment#hasValues()
52
     */
53
    public boolean hasValues() {
54
        return false;
55
    }
56
57
    /**
58
     * @see org.apache.xmlgraphics.ps.dsc.events.AbstractDSCComment#isAtend()
59
     */
60
    public boolean isAtend() {
61
        return true;
62
    }
63
64
    /**
65
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCComment#parseValue(java.lang.String)
66
     */
67
    public void parseValue(String value) {
68
        //nop
69
    }
70
    
71
    /**
72
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCEvent#generate(
73
     *              org.apache.xmlgraphics.ps.PSGenerator)
74
     */
75
    public void generate(PSGenerator gen) throws IOException {
76
        gen.writeDSCComment(getName(), DSCConstants.ATEND);
77
    }
78
79
    /**
80
     * Creates a new instance of a DSC comment with the same name as this instance but does not
81
     * have an "Atend" value.
82
     * @return the new DSC comment
83
     */
84
    public DSCComment createDSCCommentFromAtend() {
85
        return DSCCommentFactory.createDSCCommentFor(getName());
86
    }
87
88
}
0
  + native
89
  + native
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/ps/dsc/events/DSCCommentLanguageLevel.java (+87 lines)
Line 0 Link Here
1
/*
2
 * Licensed to the Apache Software Foundation (ASF) under one or more
3
 * contributor license agreements.  See the NOTICE file distributed with
4
 * this work for additional information regarding copyright ownership.
5
 * The ASF licenses this file to You under the Apache License, Version 2.0
6
 * (the "License"); you may not use this file except in compliance with
7
 * the License.  You may obtain a copy of the License at
8
 * 
9
 *      http://www.apache.org/licenses/LICENSE-2.0
10
 * 
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
18
/* $Id$ */
19
20
package org.apache.xmlgraphics.ps.dsc.events;
21
22
import java.io.IOException;
23
24
import org.apache.xmlgraphics.ps.DSCConstants;
25
import org.apache.xmlgraphics.ps.PSGenerator;
26
27
/**
28
 * Represents a %%LanguageLevel DSC comment
29
 */
30
public class DSCCommentLanguageLevel extends AbstractDSCComment {
31
32
    private int level;
33
    
34
    /**
35
     * Creates a new instance.
36
     */
37
    public DSCCommentLanguageLevel() {
38
    }
39
40
    /**
41
     * Creates a new instance
42
     * @param level the PostScript language level (usually 2 or 3)
43
     */
44
    public DSCCommentLanguageLevel(int level) {
45
        this.level = level;
46
    }
47
    
48
    /**
49
     * Returns the PostScript language level (usually 2 or 3).
50
     * @return the language level
51
     */
52
    public int getLanguageLevel() {
53
        return this.level;
54
    }
55
    
56
    /**
57
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCComment#getName()
58
     */
59
    public String getName() {
60
        return DSCConstants.LANGUAGE_LEVEL;
61
    }
62
63
    /**
64
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCComment#hasValues()
65
     */
66
    public boolean hasValues() {
67
        return true;
68
    }
69
70
    /**
71
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCComment#parseValue(java.lang.String)
72
     */
73
    public void parseValue(String value) {
74
        this.level = Integer.parseInt(value);
75
    }
76
    
77
    /**
78
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCEvent#generate(org.apache.xmlgraphics.ps.PSGenerator)
79
     */
80
    public void generate(PSGenerator gen) throws IOException {
81
        if (level <= 0) {
82
            throw new IllegalStateException("Language Level was not properly set");
83
        }
84
        gen.writeDSCComment(getName(), new Integer(getLanguageLevel()));
85
    }
86
87
}
0
  + native
88
  + native
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/ps/dsc/events/DSCCommentEndComments.java (+61 lines)
Line 0 Link Here
1
/*
2
 * Licensed to the Apache Software Foundation (ASF) under one or more
3
 * contributor license agreements.  See the NOTICE file distributed with
4
 * this work for additional information regarding copyright ownership.
5
 * The ASF licenses this file to You under the Apache License, Version 2.0
6
 * (the "License"); you may not use this file except in compliance with
7
 * the License.  You may obtain a copy of the License at
8
 * 
9
 *      http://www.apache.org/licenses/LICENSE-2.0
10
 * 
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
18
/* $Id$ */
19
20
package org.apache.xmlgraphics.ps.dsc.events;
21
22
import java.io.IOException;
23
24
import org.apache.xmlgraphics.ps.DSCConstants;
25
import org.apache.xmlgraphics.ps.PSGenerator;
26
27
/**
28
 * Respresents a %%EndComments DSC comment.
29
 */
30
public class DSCCommentEndComments extends AbstractDSCComment {
31
32
    /**
33
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCComment#getName()
34
     */
35
    public String getName() {
36
        return DSCConstants.END_COMMENTS;
37
    }
38
39
    /**
40
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCComment#hasValues()
41
     */
42
    public boolean hasValues() {
43
        return false;
44
    }
45
46
    /**
47
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCComment#parseValue(java.lang.String)
48
     */
49
    public void parseValue(String value) {
50
        //nop
51
    }
52
53
    /**
54
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCEvent#generate(
55
     *      org.apache.xmlgraphics.ps.PSGenerator)
56
     */
57
    public void generate(PSGenerator gen) throws IOException {
58
        gen.writeDSCComment(getName());
59
    }
60
61
}
0
  + native
62
  + native
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/ps/dsc/events/DSCCommentPage.java (+129 lines)
Line 0 Link Here
1
/*
2
 * Licensed to the Apache Software Foundation (ASF) under one or more
3
 * contributor license agreements.  See the NOTICE file distributed with
4
 * this work for additional information regarding copyright ownership.
5
 * The ASF licenses this file to You under the Apache License, Version 2.0
6
 * (the "License"); you may not use this file except in compliance with
7
 * the License.  You may obtain a copy of the License at
8
 * 
9
 *      http://www.apache.org/licenses/LICENSE-2.0
10
 * 
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
18
/* $Id$ */
19
20
package org.apache.xmlgraphics.ps.dsc.events;
21
22
import java.io.IOException;
23
import java.util.Iterator;
24
import java.util.List;
25
26
import org.apache.xmlgraphics.ps.DSCConstants;
27
import org.apache.xmlgraphics.ps.PSGenerator;
28
29
/**
30
 * Represents a %%Page DSC comment.
31
 */
32
public class DSCCommentPage extends AbstractDSCComment {
33
34
    private String pageName;
35
    private int pagePosition = -1;
36
    
37
    /**
38
     * Creates a new instance.
39
     */
40
    public DSCCommentPage() {
41
    }
42
43
    /**
44
     * Creates a new instance.
45
     * @param pageName the name of the page
46
     * @param pagePosition the position of the page within the file (1-based)
47
     */
48
    public DSCCommentPage(String pageName, int pagePosition) {
49
        setPageName(pageName);
50
        setPagePosition(pagePosition);
51
    }
52
    
53
    /**
54
     * Creates a new instance. The page name will be set to the same value as the page position.
55
     * @param pagePosition the position of the page within the file (1-based)
56
     */
57
    public DSCCommentPage(int pagePosition) {
58
        this(Integer.toString(pagePosition), pagePosition);
59
    }
60
61
    /**
62
     * Resturns the name of the page.
63
     * @return the page name
64
     */
65
    public String getPageName() {
66
        return this.pageName;
67
    }
68
    
69
    /**
70
     * Sets the page name.
71
     * @param name the page name
72
     */
73
    public void setPageName(String name) {
74
        this.pageName = name;
75
    }
76
77
    /**
78
     * Returns the page position.
79
     * @return the page position (1-based)
80
     */
81
    public int getPagePosition() {
82
        return this.pagePosition;
83
    }
84
    
85
    /**
86
     * Sets the page position.
87
     * @param position the page position (1-based)
88
     */
89
    public void setPagePosition(int position) {
90
        if (position <= 0) {
91
            throw new IllegalArgumentException("position must be 1 or above");
92
        }
93
        this.pagePosition = position;
94
    }
95
96
    /**
97
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCComment#getName()
98
     */
99
    public String getName() {
100
        return DSCConstants.PAGE;
101
    }
102
103
    /**
104
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCComment#hasValues()
105
     */
106
    public boolean hasValues() {
107
        return true;
108
    }
109
110
    /**
111
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCComment#parseValue(java.lang.String)
112
     */
113
    public void parseValue(String value) {
114
        List params = splitParams(value);
115
        Iterator iter = params.iterator();
116
        this.pageName = (String)iter.next();
117
        this.pagePosition = Integer.parseInt((String)iter.next());
118
    }
119
    
120
    /**
121
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCEvent#generate(
122
     *          org.apache.xmlgraphics.ps.PSGenerator)
123
     */
124
    public void generate(PSGenerator gen) throws IOException {
125
        gen.writeDSCComment(getName(), 
126
                new Object[] {getPageName(), new Integer(getPagePosition())});
127
    }
128
129
}
0
  + native
130
  + native
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/ps/dsc/events/DSCCommentDocumentNeededResources.java (+53 lines)
Line 0 Link Here
1
/*
2
 * Licensed to the Apache Software Foundation (ASF) under one or more
3
 * contributor license agreements.  See the NOTICE file distributed with
4
 * this work for additional information regarding copyright ownership.
5
 * The ASF licenses this file to You under the Apache License, Version 2.0
6
 * (the "License"); you may not use this file except in compliance with
7
 * the License.  You may obtain a copy of the License at
8
 * 
9
 *      http://www.apache.org/licenses/LICENSE-2.0
10
 * 
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
18
/* $Id$ */
19
20
package org.apache.xmlgraphics.ps.dsc.events;
21
22
import java.util.Collection;
23
24
import org.apache.xmlgraphics.ps.DSCConstants;
25
26
/**
27
 * Represents a %%DocumentNeededResources DSC comment.
28
 */
29
public class DSCCommentDocumentNeededResources extends AbstractResourcesDSCComment {
30
31
    /**
32
     * Creates a new instance.
33
     */
34
    public DSCCommentDocumentNeededResources() {
35
        super();
36
    }
37
    
38
    /**
39
     * Creates a new instance.
40
     * @param resources a Collection of PSResource instances
41
     */
42
    public DSCCommentDocumentNeededResources(Collection resources) {
43
        super(resources);
44
    }
45
    
46
    /**
47
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCComment#getName()
48
     */
49
    public String getName() {
50
        return DSCConstants.DOCUMENT_NEEDED_RESOURCES;
51
    }
52
53
}
0
  + native
54
  + native
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/ps/dsc/events/DSCComment.java (+61 lines)
Line 0 Link Here
1
/*
2
 * Licensed to the Apache Software Foundation (ASF) under one or more
3
 * contributor license agreements.  See the NOTICE file distributed with
4
 * this work for additional information regarding copyright ownership.
5
 * The ASF licenses this file to You under the Apache License, Version 2.0
6
 * (the "License"); you may not use this file except in compliance with
7
 * the License.  You may obtain a copy of the License at
8
 * 
9
 *      http://www.apache.org/licenses/LICENSE-2.0
10
 * 
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
18
/* $Id$ */
19
20
package org.apache.xmlgraphics.ps.dsc.events;
21
22
import java.io.IOException;
23
24
import org.apache.xmlgraphics.ps.PSGenerator;
25
26
/**
27
 * Base interface for all DSC comments.
28
 */
29
public interface DSCComment extends DSCEvent {
30
31
    /**
32
     * Returns the name of the DSC comment.
33
     * @return the name of the DSC comment (without the "%%" prefix)
34
     */
35
    String getName();
36
    
37
    /**
38
     * Parses the value of the DSC comment.
39
     * @param value the value
40
     */
41
    void parseValue(String value);
42
    
43
    /**
44
     * Indicates whether this DSC comment has values.
45
     * @return true if the DSC comment has values
46
     */
47
    boolean hasValues();
48
    
49
    /**
50
     * Indicates whether the DSC comment's value is "Atend".
51
     * @return true if the value is "Atend"
52
     */
53
    boolean isAtend();
54
55
    /**
56
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCEvent#generate(
57
     *      org.apache.xmlgraphics.ps.PSGenerator)
58
     */
59
    void generate(PSGenerator gen) throws IOException;
60
    
61
}
0
  + native
62
  + native
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/ps/dsc/events/DSCCommentDocumentSuppliedResources.java (+53 lines)
Line 0 Link Here
1
/*
2
 * Licensed to the Apache Software Foundation (ASF) under one or more
3
 * contributor license agreements.  See the NOTICE file distributed with
4
 * this work for additional information regarding copyright ownership.
5
 * The ASF licenses this file to You under the Apache License, Version 2.0
6
 * (the "License"); you may not use this file except in compliance with
7
 * the License.  You may obtain a copy of the License at
8
 * 
9
 *      http://www.apache.org/licenses/LICENSE-2.0
10
 * 
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
18
/* $Id$ */
19
20
package org.apache.xmlgraphics.ps.dsc.events;
21
22
import java.util.Collection;
23
24
import org.apache.xmlgraphics.ps.DSCConstants;
25
26
/**
27
 * Represents a %%DocumentSuppliedResources DSC comment.
28
 */
29
public class DSCCommentDocumentSuppliedResources extends AbstractResourcesDSCComment {
30
31
    /**
32
     * Creates a new instance.
33
     */
34
    public DSCCommentDocumentSuppliedResources() {
35
        super();
36
    }
37
    
38
    /**
39
     * Creates a new instance.
40
     * @param resources a Collection of PSResource instances
41
     */
42
    public DSCCommentDocumentSuppliedResources(Collection resources) {
43
        super(resources);
44
    }
45
    
46
    /**
47
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCComment#getName()
48
     */
49
    public String getName() {
50
        return DSCConstants.DOCUMENT_SUPPLIED_RESOURCES;
51
    }
52
53
}
0
  + native
54
  + native
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/ps/dsc/events/PostScriptComment.java (+74 lines)
Line 0 Link Here
1
/*
2
 * Licensed to the Apache Software Foundation (ASF) under one or more
3
 * contributor license agreements.  See the NOTICE file distributed with
4
 * this work for additional information regarding copyright ownership.
5
 * The ASF licenses this file to You under the Apache License, Version 2.0
6
 * (the "License"); you may not use this file except in compliance with
7
 * the License.  You may obtain a copy of the License at
8
 * 
9
 *      http://www.apache.org/licenses/LICENSE-2.0
10
 * 
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
18
/* $Id$ */
19
20
package org.apache.xmlgraphics.ps.dsc.events;
21
22
import java.io.IOException;
23
24
import org.apache.xmlgraphics.ps.PSGenerator;
25
26
/**
27
 * Represents a PostScript comment
28
 */
29
public class PostScriptComment extends AbstractEvent {
30
31
    private String comment;
32
    
33
    /**
34
     * Creates a new instance.
35
     * @param comment the comment
36
     */
37
    public PostScriptComment(String comment) {
38
        if (comment != null && comment.startsWith("%")) {
39
            this.comment = this.comment.substring(1);
40
        } else {
41
            this.comment = comment;
42
        }
43
    }
44
    
45
    /**
46
     * Returns the comment text.
47
     * @return the comment (without the "%" prefix)
48
     */
49
    public String getComment() {
50
        return this.comment;
51
    }
52
    
53
    /**
54
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCEvent#generate(org.apache.xmlgraphics.ps.PSGenerator)
55
     */
56
    public void generate(PSGenerator gen) throws IOException {
57
        gen.commentln("%" + getComment());
58
    }
59
60
    /**
61
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCEvent#getEventType()
62
     */
63
    public int getEventType() {
64
        return COMMENT;
65
    }
66
67
    /**
68
     * @see org.apache.xmlgraphics.ps.dsc.events.AbstractEvent#isComment()
69
     */
70
    public boolean isComment() {
71
        return true;
72
    }
73
74
}
0
  + native
75
  + native
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/ps/dsc/events/UnparsedDSCComment.java (+100 lines)
Line 0 Link Here
1
/*
2
 * Licensed to the Apache Software Foundation (ASF) under one or more
3
 * contributor license agreements.  See the NOTICE file distributed with
4
 * this work for additional information regarding copyright ownership.
5
 * The ASF licenses this file to You under the Apache License, Version 2.0
6
 * (the "License"); you may not use this file except in compliance with
7
 * the License.  You may obtain a copy of the License at
8
 * 
9
 *      http://www.apache.org/licenses/LICENSE-2.0
10
 * 
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
18
/* $Id$ */
19
20
package org.apache.xmlgraphics.ps.dsc.events;
21
22
import java.io.IOException;
23
24
import org.apache.xmlgraphics.ps.PSGenerator;
25
26
/**
27
 * Represents a DSC comment that is not parsed into one of the concrete DSCComment subclasses.
28
 * It is used whenever a DSC comment is encountered that is unknown to the parser.
29
 * @see org.apache.xmlgraphics.ps.dsc.DSCCommentFactory
30
 */
31
public class UnparsedDSCComment extends AbstractEvent implements DSCComment {
32
33
    private String name;
34
    private String value;
35
    
36
    /**
37
     * Creates a new instance.
38
     * @param name the name of the DSC comment
39
     */
40
    public UnparsedDSCComment(String name) {
41
        this.name = name;
42
    }
43
    
44
    /**
45
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCComment#getName()
46
     */
47
    public String getName() {
48
        return this.name;
49
    }
50
51
    /**
52
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCComment#hasValues()
53
     */
54
    public boolean hasValues() {
55
        return value != null;
56
    }
57
58
    /**
59
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCComment#isAtend()
60
     */
61
    public boolean isAtend() {
62
        return false;
63
    }
64
65
    /**
66
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCComment#parseValue(java.lang.String)
67
     */
68
    public void parseValue(String value) {
69
        this.value = value;
70
    }
71
72
    /**
73
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCEvent#generate(org.apache.xmlgraphics.ps.PSGenerator)
74
     */
75
    public void generate(PSGenerator gen) throws IOException {
76
        gen.writeln("%%" + name + (hasValues() ? ": " + value : ""));
77
    }
78
79
    /**
80
     * @see org.apache.xmlgraphics.ps.dsc.events.AbstractEvent#isDSCComment()
81
     */
82
    public boolean isDSCComment() {
83
        return true;
84
    }
85
86
    /**
87
     * @see org.apache.xmlgraphics.ps.dsc.events.DSCEvent#getEventType()
88
     */
89
    public int getEventType() {
90
        return DSC_COMMENT;
91
    }
92
93
    /**
94
     * @see org.apache.xmlgraphics.ps.dsc.events.AbstractEvent#asDSCComment()
95
     */
96
    public DSCComment asDSCComment() {
97
        return this;
98
    }
99
100
}
0
  + native
101
  + native
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/ps/dsc/DSCCommentFactory.java (+87 lines)
Line 0 Link Here
1
/*
2
 * Licensed to the Apache Software Foundation (ASF) under one or more
3
 * contributor license agreements.  See the NOTICE file distributed with
4
 * this work for additional information regarding copyright ownership.
5
 * The ASF licenses this file to You under the Apache License, Version 2.0
6
 * (the "License"); you may not use this file except in compliance with
7
 * the License.  You may obtain a copy of the License at
8
 * 
9
 *      http://www.apache.org/licenses/LICENSE-2.0
10
 * 
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
18
/* $Id$ */
19
20
package org.apache.xmlgraphics.ps.dsc;
21
22
import java.util.Map;
23
24
import org.apache.xmlgraphics.ps.DSCConstants;
25
import org.apache.xmlgraphics.ps.dsc.events.DSCComment;
26
import org.apache.xmlgraphics.ps.dsc.events.DSCCommentBeginResource;
27
import org.apache.xmlgraphics.ps.dsc.events.DSCCommentDocumentNeededResources;
28
import org.apache.xmlgraphics.ps.dsc.events.DSCCommentDocumentSuppliedResources;
29
import org.apache.xmlgraphics.ps.dsc.events.DSCCommentEndComments;
30
import org.apache.xmlgraphics.ps.dsc.events.DSCCommentLanguageLevel;
31
import org.apache.xmlgraphics.ps.dsc.events.DSCCommentPage;
32
import org.apache.xmlgraphics.ps.dsc.events.DSCCommentPageResources;
33
import org.apache.xmlgraphics.ps.dsc.events.DSCCommentPages;
34
import org.apache.xmlgraphics.ps.dsc.events.DSCCommentEndOfFile;
35
36
/**
37
 * Factory for DSCComment subclasses.
38
 */
39
public class DSCCommentFactory {
40
41
    private static final Map DSC_FACTORIES = new java.util.HashMap();
42
43
    static {
44
        DSC_FACTORIES.put(DSCConstants.END_COMMENTS, 
45
                DSCCommentEndComments.class);
46
        DSC_FACTORIES.put(DSCConstants.BEGIN_RESOURCE, 
47
                DSCCommentBeginResource.class);
48
        DSC_FACTORIES.put(DSCConstants.PAGE_RESOURCES, 
49
                DSCCommentPageResources.class);
50
        DSC_FACTORIES.put(DSCConstants.PAGE, 
51
                DSCCommentPage.class);
52
        DSC_FACTORIES.put(DSCConstants.PAGES, 
53
                DSCCommentPages.class);
54
        DSC_FACTORIES.put(DSCConstants.LANGUAGE_LEVEL, 
55
                DSCCommentLanguageLevel.class);
56
        DSC_FACTORIES.put(DSCConstants.DOCUMENT_NEEDED_RESOURCES, 
57
                DSCCommentDocumentNeededResources.class);
58
        DSC_FACTORIES.put(DSCConstants.DOCUMENT_SUPPLIED_RESOURCES, 
59
                DSCCommentDocumentSuppliedResources.class);
60
        DSC_FACTORIES.put(DSCConstants.EOF, 
61
                DSCCommentEndOfFile.class);
62
        //TODO Add additional implementations as needed
63
    }
64
    
65
    /**
66
     * Creates and returns new instances for DSC comments with a given name.
67
     * @param name the name of the DSCComment (without the "%%" prefix)
68
     * @return the new instance or null if no particular subclass registered for the given
69
     *          DSC comment.
70
     */
71
    public static DSCComment createDSCCommentFor(String name) {
72
        Class clazz = (Class)DSC_FACTORIES.get(name);
73
        if (clazz == null) {
74
            return null;
75
        }
76
        try {
77
            return (DSCComment)clazz.newInstance();
78
        } catch (InstantiationException e) {
79
            throw new RuntimeException("Error instantiating instance for '" + name + "': " 
80
                    + e.getMessage());
81
        } catch (IllegalAccessException e) {
82
            throw new RuntimeException("Illegal Access error while instantiating instance for '" 
83
                    + name + "': " + e.getMessage());
84
        }
85
    }
86
    
87
}
0
  + native
88
  + native
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/ps/dsc/DefaultNestedDocumentHandler.java (+73 lines)
Line 0 Link Here
1
/*
2
 * Licensed to the Apache Software Foundation (ASF) under one or more
3
 * contributor license agreements.  See the NOTICE file distributed with
4
 * this work for additional information regarding copyright ownership.
5
 * The ASF licenses this file to You under the Apache License, Version 2.0
6
 * (the "License"); you may not use this file except in compliance with
7
 * the License.  You may obtain a copy of the License at
8
 * 
9
 *      http://www.apache.org/licenses/LICENSE-2.0
10
 * 
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
18
/* $Id$ */
19
20
package org.apache.xmlgraphics.ps.dsc;
21
22
import java.io.IOException;
23
24
import org.apache.xmlgraphics.ps.DSCConstants;
25
import org.apache.xmlgraphics.ps.PSGenerator;
26
import org.apache.xmlgraphics.ps.dsc.events.DSCComment;
27
import org.apache.xmlgraphics.ps.dsc.events.DSCEvent;
28
29
/**
30
 * Default implementation of the NestedDocumentHandler interface which automatically skips data
31
 * between Begin/EndDocument and Begin/EndData.
32
 */
33
public class DefaultNestedDocumentHandler implements DSCParserConstants, NestedDocumentHandler {
34
35
    private PSGenerator gen;
36
    
37
    /**
38
     * Creates a new instance.
39
     * @param gen PSGenerator to pass through the skipped content
40
     */
41
    public DefaultNestedDocumentHandler(PSGenerator gen) {
42
        this.gen = gen;
43
    }
44
    
45
    /**
46
     * @see org.apache.xmlgraphics.ps.dsc.NestedDocumentHandler#handle(org.apache.xmlgraphics.ps.dsc.events.DSCEvent, org.apache.xmlgraphics.ps.dsc.DSCParser)
47
     */
48
    public void handle(DSCEvent event, DSCParser parser) throws IOException, DSCException {
49
        if (event.isDSCComment()) {
50
            DSCComment comment = event.asDSCComment();
51
            if (DSCConstants.BEGIN_DOCUMENT.equals(comment.getName())) {
52
                comment.generate(gen);
53
                comment = parser.nextDSCComment(DSCConstants.END_DOCUMENT, gen);
54
                if (comment == null) {
55
                    throw new DSCException("File is not DSC-compliant: Didn't find an " 
56
                            + DSCConstants.END_DOCUMENT);
57
                }
58
                comment.generate(gen);
59
                parser.next();
60
            } else if (DSCConstants.BEGIN_DATA.equals(comment.getName())) {
61
                comment.generate(gen);
62
                comment = parser.nextDSCComment(DSCConstants.END_DATA, gen);
63
                if (comment == null) {
64
                    throw new DSCException("File is not DSC-compliant: Didn't find an " 
65
                            + DSCConstants.END_DATA);
66
                }
67
                comment.generate(gen);
68
                parser.next();
69
            } 
70
        }
71
    }
72
    
73
}
0
  + native
74
  + native
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/ps/dsc/DSCParser.java (+385 lines)
Line 0 Link Here
1
/*
2
 * Licensed to the Apache Software Foundation (ASF) under one or more
3
 * contributor license agreements.  See the NOTICE file distributed with
4
 * this work for additional information regarding copyright ownership.
5
 * The ASF licenses this file to You under the Apache License, Version 2.0
6
 * (the "License"); you may not use this file except in compliance with
7
 * the License.  You may obtain a copy of the License at
8
 * 
9
 *      http://www.apache.org/licenses/LICENSE-2.0
10
 * 
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
18
/* $Id$ */
19
 
20
package org.apache.xmlgraphics.ps.dsc;
21
22
import java.io.BufferedReader;
23
import java.io.IOException;
24
import java.io.InputStream;
25
import java.io.UnsupportedEncodingException;
26
import java.util.NoSuchElementException;
27
28
import org.apache.xmlgraphics.ps.DSCConstants;
29
import org.apache.xmlgraphics.ps.PSGenerator;
30
import org.apache.xmlgraphics.ps.dsc.events.DSCAtend;
31
import org.apache.xmlgraphics.ps.dsc.events.DSCComment;
32
import org.apache.xmlgraphics.ps.dsc.events.DSCEvent;
33
import org.apache.xmlgraphics.ps.dsc.events.DSCHeaderComment;
34
import org.apache.xmlgraphics.ps.dsc.events.PostScriptComment;
35
import org.apache.xmlgraphics.ps.dsc.events.PostScriptLine;
36
import org.apache.xmlgraphics.ps.dsc.events.UnparsedDSCComment;
37
import org.apache.xmlgraphics.ps.dsc.tools.DSCTools;
38
39
/**
40
 * Parser for DSC-compliant PostScript files (DSC = Document Structuring Conventions). The parser
41
 * is implemented as a pull parser but has the ability to act as a push parser through the 
42
 * DSCHandler interface.
43
 */
44
public class DSCParser implements DSCParserConstants {
45
46
    private InputStream in;
47
    private BufferedReader reader;
48
    private boolean eofFound = false;
49
    private DSCEvent currentEvent;
50
    private DSCEvent nextEvent;
51
    private DSCFilter filter;
52
    private NestedDocumentHandler nestedDocumentHandler;
53
    
54
    /**
55
     * Creates a new DSC parser.
56
     * @param in InputStream to read the PostScript file from
57
     *              (the stream is not closed by this class, the caller is responsible for that)
58
     * @throws IOException In case of an I/O error
59
     * @throws DSCException In case of a violation of the DSC spec
60
     */
61
    public DSCParser(InputStream in) throws IOException, DSCException {
62
        if (in.markSupported()) {
63
            this.in = in;
64
        } else {
65
            //Decorate for better performance
66
            this.in = new java.io.BufferedInputStream(this.in);
67
        }
68
        String encoding = "US-ASCII";
69
        try {
70
            this.reader = new java.io.BufferedReader(
71
                    new java.io.InputStreamReader(this.in, encoding));
72
        } catch (UnsupportedEncodingException e) {
73
            throw new RuntimeException("Incompatible VM! " + e.getMessage());
74
        }
75
        parseNext();
76
    }
77
    
78
    /**
79
     * Returns the InputStream the PostScript code is read from.
80
     * @return the InputStream the PostScript code is read from
81
     */
82
    public InputStream getInputStream() {
83
        return this.in;
84
    }
85
    
86
    /**
87
     * This method is used to write out warning messages for the parsing process. Subclass to
88
     * override this method. The default implementation writes to System.err.
89
     * @param msg the warning message
90
     */
91
    protected void warn(String msg) {
92
        System.err.println(msg);
93
    }
94
    
95
    /**
96
     * Reads one line from the input file
97
     * @return the line or null if there are no more lines
98
     * @throws IOException In case of an I/O error
99
     * @throws DSCException In case of a violation of the DSC spec
100
     */
101
    protected String readLine() throws IOException, DSCException {
102
        String line;
103
        line = this.reader.readLine();
104
        checkLine(line);
105
        
106
        return line;
107
    }
108
109
    private void checkLine(String line) throws DSCException {
110
        if (line == null) {
111
            if (!eofFound) {
112
                throw new DSCException("%%EOF not found. File is not well-formed.");
113
            }
114
        } else if (line.length() > 255) {
115
            warn("Line longer than 255 characters. This file is not fully PostScript conforming.");
116
        }
117
    }
118
    
119
    private final boolean isWhitespace(char c) {
120
        return c == ' ' || c == '\t';
121
    }
122
    
123
    private DSCComment parseDSCLine(String line) throws IOException, DSCException {
124
        int colon = line.indexOf(':');
125
        String name, value;
126
        if (colon > 0) {
127
            name = line.substring(2, colon);
128
            int startOfValue = colon + 1;
129
            if (isWhitespace(line.charAt(startOfValue))) {
130
                startOfValue++;
131
            }
132
            value = line.substring(startOfValue).trim();
133
            if (value.equals(DSCConstants.ATEND.toString())) {
134
                return new DSCAtend(name);
135
            }
136
            String nextLine;
137
            while (true) {
138
                this.reader.mark(512);
139
                nextLine = readLine();
140
                if (nextLine == null) {
141
                    break;
142
                } else if (!nextLine.startsWith("%%+")) {
143
                    break;
144
                }
145
                value = value + nextLine.substring(3);
146
            }
147
            this.reader.reset();
148
        } else {
149
            name = line.substring(2);
150
            value = null;
151
        }
152
        return parseDSCComment(name, value);
153
    }
154
155
    private DSCComment parseDSCComment(String name, String value) {
156
        DSCComment parsed = DSCCommentFactory.createDSCCommentFor(name);
157
        if (parsed != null) {
158
            parsed.parseValue(value);
159
            return parsed;
160
        } else {
161
            UnparsedDSCComment unparsed = new UnparsedDSCComment(name);
162
            unparsed.parseValue(value);
163
            return unparsed;
164
        }
165
    }
166
167
    /**
168
     * Starts the parser in push parsing mode sending events to the DSCHandler instance.
169
     * @param handler the DSCHandler instance to send the events to
170
     * @throws IOException In case of an I/O error
171
     * @throws DSCException In case of a violation of the DSC spec
172
     */
173
    public void parse(DSCHandler handler) throws IOException, DSCException {
174
        DSCHeaderComment header = DSCTools.checkAndSkipDSC30Header(this);
175
        handler.startDocument("%!" + header.getComment());
176
        DSCEvent event;
177
        while (hasNext()) {
178
            event = nextEvent();
179
            switch (event.getEventType()) {
180
            case HEADER_COMMENT:
181
                handler.startDocument("%!" + ((DSCHeaderComment)event).getComment());
182
                break;
183
            case DSC_COMMENT:
184
                handler.handleDSCComment(event.asDSCComment());
185
                break;
186
            case COMMENT:
187
                handler.comment(((PostScriptComment)event).getComment());
188
                break;
189
            case LINE:
190
                handler.line(getLine());
191
                break;
192
            case EOF:
193
                this.eofFound = true;
194
                handler.endDocument();
195
                break;
196
            default:
197
                throw new IllegalStateException("Illegal event type: " + event.getEventType());
198
            }
199
        }
200
    }
201
    
202
    /**
203
     * Indicates whether there are additional items.
204
     * @return true if there are additonal items, false if the end of the file has been reached
205
     */
206
    public boolean hasNext() {
207
        return (this.nextEvent != null);
208
    }
209
210
    /**
211
     * Steps to the next item indicating the type of event.
212
     * @return the type of event (See {@link DSCParserConstants})
213
     * @throws IOException In case of an I/O error
214
     * @throws DSCException In case of a violation of the DSC spec
215
     * @throws NoSuchElementException If an attempt was made to advance beyond the end of the file
216
     */
217
    public int next() throws IOException, DSCException {
218
        if (hasNext()) {
219
            this.currentEvent = nextEvent;
220
            parseNext();
221
            if (this.nestedDocumentHandler != null) {
222
                this.nestedDocumentHandler.handle(this.currentEvent, this);
223
            }
224
            return this.currentEvent.getEventType();
225
        } else {
226
            throw new NoSuchElementException("There are no more events");
227
        }
228
    }
229
    
230
    /**
231
     * Steps to the next item returning the new event.
232
     * @return the new event
233
     * @throws IOException In case of an I/O error
234
     * @throws DSCException In case of a violation of the DSC spec
235
     */
236
    public DSCEvent nextEvent() throws IOException, DSCException {
237
        next();
238
        return getCurrentEvent();
239
    }
240
    
241
    /**
242
     * Returns the current event.
243
     * @return the current event
244
     */
245
    public DSCEvent getCurrentEvent() {
246
        return this.currentEvent;
247
    }
248
    
249
    /**
250
     * Returns the next event without moving the cursor to the next event.
251
     * @return the next event
252
     */
253
    public DSCEvent peek() {
254
        return this.nextEvent;
255
    }
256
    
257
    /**
258
     * Parses the next event.
259
     * @throws IOException In case of an I/O error
260
     * @throws DSCException In case of a violation of the DSC spec
261
     */
262
    protected void parseNext() throws IOException, DSCException {
263
        String line = readLine();
264
        if (line != null) {
265
            if (eofFound && (line.length() > 0)) {
266
                throw new DSCException("Content found after EOF");
267
            }
268
            if (line.startsWith("%%")) {
269
                DSCComment comment = parseDSCLine(line);
270
                if (comment.getEventType() == EOF) {
271
                    this.eofFound = true;
272
                }
273
                this.nextEvent = comment;
274
            } else if (line.startsWith("%!")) {
275
                this.nextEvent = new DSCHeaderComment(line.substring(2));
276
            } else if (line.startsWith("%")) {
277
                this.nextEvent = new PostScriptComment(line.substring(1));
278
            } else {
279
                this.nextEvent = new PostScriptLine(line);
280
            }
281
            if (this.filter != null && !filter.accept(this.nextEvent)) {
282
                parseNext(); //skip
283
            }
284
        } else {
285
            this.nextEvent = null;
286
        }
287
    }
288
    
289
    /**
290
     * Returns the current PostScript line.
291
     * @return the current PostScript line
292
     * @throws IllegalStateException if the current event is not a normal PostScript line
293
     */
294
    public String getLine() {
295
        if (this.currentEvent.getEventType() == LINE) {
296
            return ((PostScriptLine)this.currentEvent).getLine();
297
        } else {
298
            throw new IllegalStateException("Current event is not a PostScript line");
299
        }
300
    }
301
302
    /**
303
     * Advances to the next DSC comment with the given name.
304
     * @param name the name of the DSC comment
305
     * @return the requested DSC comment or null if the end of the file is reached
306
     * @throws IOException In case of an I/O error
307
     * @throws DSCException In case of a violation of the DSC spec
308
     */
309
    public DSCComment nextDSCComment(String name) 
310
                throws IOException, DSCException {
311
        return nextDSCComment(name, null);
312
    }
313
    
314
    /**
315
     * Advances to the next DSC comment with the given name.
316
     * @param name the name of the DSC comment
317
     * @param gen PSGenerator to pass the skipped events though to
318
     * @return the requested DSC comment or null if the end of the file is reached
319
     * @throws IOException In case of an I/O error
320
     * @throws DSCException In case of a violation of the DSC spec
321
     */
322
    public DSCComment nextDSCComment(String name, PSGenerator gen) 
323
                throws IOException, DSCException {
324
        while (hasNext()) {
325
            DSCEvent event = nextEvent();
326
            if (event.isDSCComment()) {
327
                DSCComment comment = event.asDSCComment();
328
                if (name.equals(comment.getName())) {
329
                    return comment;
330
                }
331
            }
332
            if (gen != null) {
333
                event.generate(gen); //Pipe through to PSGenerator
334
            }
335
        }
336
        return null;
337
    }
338
339
    /**
340
     * Advances to the next PostScript comment with the given prefix. This is used to find
341
     * comments following the DSC extension mechanism.
342
     * <p>
343
     * Example: To find FOP's custom comments, pass in "FOP" as a prefix. This will find comments
344
     * like "%FOPFontSetup".
345
     * @param prefix the prefix of the extension comment
346
     * @param gen PSGenerator to pass the skipped events though to
347
     * @return the requested PostScript comment or null if the end of the file is reached
348
     * @throws IOException In case of an I/O error
349
     * @throws DSCException In case of a violation of the DSC spec
350
     */
351
    public PostScriptComment nextPSComment(String prefix, PSGenerator gen)
352
                    throws IOException, DSCException {
353
            while (hasNext()) {
354
                DSCEvent event = nextEvent();
355
                if (event.isComment()) {
356
                    PostScriptComment comment = (PostScriptComment)event;
357
                    if (comment.getComment().startsWith(prefix)) {
358
                        return comment;
359
                    }
360
                }
361
                if (gen != null) {
362
                    event.generate(gen); //Pipe through to PSGenerator
363
                }
364
            }
365
            return null;
366
    }
367
368
    /**
369
     * Sets a filter for DSC events.
370
     * @param filter the filter to use or null to disable filtering
371
     */
372
    public void setFilter(DSCFilter filter) {
373
        this.filter = filter;
374
    }
375
376
    /**
377
     * Sets a NestedDocumentHandler which is used to skip nested documents like embedded EPS files.
378
     * You can also process those parts in a special way.
379
     * @param handler the NestedDocumentHandler instance or null to disable the feature
380
     */
381
    public void setNestedDocumentHandler(NestedDocumentHandler handler) {
382
        this.nestedDocumentHandler = handler;
383
    }
384
385
}
0
  + native
386
  + native
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/ps/dsc/EventRecorder.java (+120 lines)
Line 0 Link Here
1
/*
2
 * Licensed to the Apache Software Foundation (ASF) under one or more
3
 * contributor license agreements.  See the NOTICE file distributed with
4
 * this work for additional information regarding copyright ownership.
5
 * The ASF licenses this file to You under the Apache License, Version 2.0
6
 * (the "License"); you may not use this file except in compliance with
7
 * the License.  You may obtain a copy of the License at
8
 * 
9
 *      http://www.apache.org/licenses/LICENSE-2.0
10
 * 
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
18
/* $Id$ */
19
 
20
package org.apache.xmlgraphics.ps.dsc;
21
22
import java.io.IOException;
23
import java.util.Iterator;
24
import java.util.List;
25
26
import org.apache.xmlgraphics.ps.dsc.events.DSCComment;
27
28
/**
29
 * DSCHandler implementation that records DSC events.
30
 */
31
public class EventRecorder implements DSCHandler {
32
33
    private List events = new java.util.ArrayList();
34
    
35
    /**
36
     * Replays the recorded events to a specified DSCHandler instance.
37
     * @param handler the DSCHandler to send the recorded events to
38
     * @throws IOException In case of an I/O error
39
     */
40
    public void replay(DSCHandler handler) throws IOException {
41
        Iterator iter = events.iterator();
42
        while (iter.hasNext()) {
43
            Object obj = iter.next();
44
            if (obj instanceof PSLine) {
45
                handler.line(((PSLine)obj).getLine());
46
            } else if (obj instanceof PSComment) {
47
                handler.comment(((PSComment)obj).getComment()); 
48
            } else if (obj instanceof DSCComment) {
49
                handler.handleDSCComment((DSCComment)obj);
50
            } else {
51
                throw new IllegalStateException("Unsupported class type");
52
            }
53
        }
54
    }
55
    
56
    /**
57
     * @see org.apache.xmlgraphics.ps.dsc.DSCHandler#comment(java.lang.String)
58
     */
59
    public void comment(String comment) throws IOException {
60
        events.add(new PSComment(comment));
61
    }
62
63
    /**
64
     * @see org.apache.xmlgraphics.ps.dsc.DSCHandler#handleDSCComment(
65
     *          org.apache.xmlgraphics.ps.dsc.events.DSCComment)
66
     */
67
    public void handleDSCComment(DSCComment comment) throws IOException {
68
        events.add(comment);
69
    }
70
71
    /**
72
     * @see org.apache.xmlgraphics.ps.dsc.DSCHandler#line(java.lang.String)
73
     */
74
    public void line(String line) throws IOException {
75
        events.add(new PSLine(line));
76
    }
77
78
    /**
79
     * @see org.apache.xmlgraphics.ps.dsc.DSCHandler#startDocument(java.lang.String)
80
     */
81
    public void startDocument(String header) throws IOException {
82
        throw new UnsupportedOperationException(
83
                getClass().getName() + " is only used to handle parts of a document");
84
    }
85
86
    /**
87
     * @see org.apache.xmlgraphics.ps.dsc.DSCHandler#endDocument()
88
     */
89
    public void endDocument() throws IOException {
90
        throw new UnsupportedOperationException(
91
                getClass().getName() + " is only used to handle parts of a document");
92
    }
93
94
    private static class PSComment {
95
        
96
        private String comment;
97
        
98
        public PSComment(String comment) {
99
            this.comment = comment;
100
        }
101
        
102
        public String getComment() {
103
            return this.comment;
104
        }
105
    }
106
    
107
    private static class PSLine {
108
        
109
        private String line;
110
        
111
        public PSLine(String line) {
112
            this.line = line;
113
        }
114
        
115
        public String getLine() {
116
            return this.line;
117
        }
118
    }
119
    
120
}
0
  + native
121
  + native
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/ps/dsc/DSCHandler.java (+68 lines)
Line 0 Link Here
1
/*
2
 * Licensed to the Apache Software Foundation (ASF) under one or more
3
 * contributor license agreements.  See the NOTICE file distributed with
4
 * this work for additional information regarding copyright ownership.
5
 * The ASF licenses this file to You under the Apache License, Version 2.0
6
 * (the "License"); you may not use this file except in compliance with
7
 * the License.  You may obtain a copy of the License at
8
 * 
9
 *      http://www.apache.org/licenses/LICENSE-2.0
10
 * 
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
18
/* $Id$ */
19
 
20
package org.apache.xmlgraphics.ps.dsc;
21
22
import java.io.IOException;
23
24
import org.apache.xmlgraphics.ps.dsc.events.DSCComment;
25
26
/**
27
 * Interface containing events generated by the DSCParser. Applications can implement this
28
 * interface to react to certain events.
29
 */
30
public interface DSCHandler {
31
32
    /**
33
     * Called as a new PostScript file starts.
34
     * @param header the first line of the DSC-compliant file
35
     * @throws IOException In case of an I/O error
36
     */
37
    public void startDocument(String header) throws IOException;
38
    
39
    /**
40
     * Called when the PostScript file is fully processed, i.e. after the %%EOF comment.
41
     * @throws IOException In case of an I/O error
42
     */
43
    public void endDocument() throws IOException;
44
45
    /**
46
     * Called for each standard DSC comment. The classes passed to this method may be simple
47
     * DSCComment classes or special subclasses for some of the DSC comments.
48
     * @param comment the DSC comment
49
     * @throws IOException In case of an I/O error
50
     */
51
    public void handleDSCComment(DSCComment comment) throws IOException;
52
53
    /**
54
     * Called for a normal line of PostScript code.
55
     * @param line the line of code
56
     * @throws IOException In case of an I/O error
57
     */
58
    public void line(String line) throws IOException;
59
60
    /**
61
     * Called for any line containing a full-line PostScript comment. This is also called for
62
     * custom comments following the extension mechanism of the DSC specification.
63
     * @param comment the comment line
64
     * @throws IOException In case of an I/O error
65
     */
66
    public void comment(String comment) throws IOException;
67
    
68
}
0
  + native
69
  + native
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/ps/dsc/DSCException.java (+37 lines)
Line 0 Link Here
1
/*
2
 * Licensed to the Apache Software Foundation (ASF) under one or more
3
 * contributor license agreements.  See the NOTICE file distributed with
4
 * this work for additional information regarding copyright ownership.
5
 * The ASF licenses this file to You under the Apache License, Version 2.0
6
 * (the "License"); you may not use this file except in compliance with
7
 * the License.  You may obtain a copy of the License at
8
 * 
9
 *      http://www.apache.org/licenses/LICENSE-2.0
10
 * 
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
18
/* $Id$ */
19
 
20
package org.apache.xmlgraphics.ps.dsc;
21
22
/**
23
 * Exception to signal problems while parsing a supposedly DSC-conformant file.
24
 */
25
public class DSCException extends Exception {
26
27
    private static final long serialVersionUID = -1549406547978409615L;
28
29
    /**
30
     * Creates a new DSCException.
31
     * @param msg the exception message
32
     */
33
    public DSCException(String msg) {
34
        super(msg);
35
    }
36
    
37
}
0
  + native
38
  + native
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/ps/dsc/DefaultDSCHandler.java (+77 lines)
Line 0 Link Here
1
/*
2
 * Licensed to the Apache Software Foundation (ASF) under one or more
3
 * contributor license agreements.  See the NOTICE file distributed with
4
 * this work for additional information regarding copyright ownership.
5
 * The ASF licenses this file to You under the Apache License, Version 2.0
6
 * (the "License"); you may not use this file except in compliance with
7
 * the License.  You may obtain a copy of the License at
8
 * 
9
 *      http://www.apache.org/licenses/LICENSE-2.0
10
 * 
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
18
/* $Id$ */
19
 
20
package org.apache.xmlgraphics.ps.dsc;
21
22
import java.io.IOException;
23
import java.io.OutputStream;
24
25
import org.apache.xmlgraphics.ps.DSCConstants;
26
import org.apache.xmlgraphics.ps.PSGenerator;
27
import org.apache.xmlgraphics.ps.dsc.events.DSCComment;
28
29
/**
30
 * Default implementation of a DSCHandler which simply passes through the PostScript content
31
 * unchanged. Subclasses can implement different behaviour, for example to filter certain
32
 * DSC comments or to insert PostScript code at specific places.
33
 */
34
public class DefaultDSCHandler implements DSCHandler {
35
36
    protected OutputStream out;
37
    protected PSGenerator gen;
38
    
39
    /**
40
     * Creates a new instance.
41
     * @param out OutputStream to pipe all received events to
42
     */
43
    public DefaultDSCHandler(OutputStream out) {
44
        this.out = out;
45
        this.gen = new PSGenerator(this.out);
46
    }
47
    
48
    /** @see org.apache.xmlgraphics.ps.dsc.DSCHandler#startDocument(java.lang.String) */
49
    public void startDocument(String header) throws IOException {
50
        gen.writeln(header);
51
    }
52
53
    /** @see org.apache.xmlgraphics.ps.dsc.DSCHandler#endDocument() */
54
    public void endDocument() throws IOException {
55
        gen.writeDSCComment(DSCConstants.EOF);
56
    }
57
58
    /**
59
     * @see org.apache.xmlgraphics.ps.dsc.DSCHandler#handleDSCComment(
60
     *      org.apache.xmlgraphics.ps.dsc.events.DSCComment)
61
     */
62
    public void handleDSCComment(DSCComment comment) throws IOException {
63
        comment.generate(gen);
64
        
65
    }
66
67
    /** @see org.apache.xmlgraphics.ps.dsc.DSCHandler#line(java.lang.String) */
68
    public void line(String line) throws IOException {
69
        gen.writeln(line);
70
    }
71
72
    /** @see org.apache.xmlgraphics.ps.dsc.DSCHandler#comment(java.lang.String) */
73
    public void comment(String comment) throws IOException {
74
        gen.commentln("%" + comment);
75
    }
76
77
}
0
  + native
78
  + native
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/ps/dsc/package.html (+23 lines)
Line 0 Link Here
1
<!--
2
  Licensed to the Apache Software Foundation (ASF) under one or more
3
  contributor license agreements.  See the NOTICE file distributed with
4
  this work for additional information regarding copyright ownership.
5
  The ASF licenses this file to You under the Apache License, Version 2.0
6
  (the "License"); you may not use this file except in compliance with
7
  the License.  You may obtain a copy of the License at
8
9
       http://www.apache.org/licenses/LICENSE-2.0
10
11
  Unless required by applicable law or agreed to in writing, software
12
  distributed under the License is distributed on an "AS IS" BASIS,
13
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
  See the License for the specific language governing permissions and
15
  limitations under the License.
16
-->
17
<!-- $Id$ -->
18
<HTML>
19
<TITLE>org.apache.xmlgraphics.ps.dsc Package</TITLE>
20
<BODY>
21
<P>Tools for DSC-compliant PostScript files (DSC = Document Structuring Conventions).</P>
22
</BODY>
23
</HTML>
0
  + native
24
  + native
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/ps/PSResource.java (+28 lines)
Lines 30-35 Link Here
30
    public static final String TYPE_FONT = "font";
30
    public static final String TYPE_FONT = "font";
31
    /** a procset resource */
31
    /** a procset resource */
32
    public static final String TYPE_PROCSET = "procset";
32
    public static final String TYPE_PROCSET = "procset";
33
    /** a procset resource */
34
    public static final String TYPE_PATTERN = "pattern";
35
    /** a procset resource */
36
    public static final String TYPE_FORM = "form";
37
    /** a procset resource */
38
    public static final String TYPE_ENCODING = "encoding";
33
    
39
    
34
    private String type;
40
    private String type;
35
    private String name;
41
    private String name;
Lines 61-64 Link Here
61
        return sb.toString();
67
        return sb.toString();
62
    }
68
    }
63
    
69
    
70
    
71
    /** @see java.lang.Object#equals(java.lang.Object) */
72
    public boolean equals(Object obj) {
73
        if (obj == this) {
74
            return true;
75
        } else if (obj instanceof PSResource) {
76
            PSResource other = (PSResource)obj;
77
            return other.toString().equals(toString());
78
        } else {
79
            return false;
80
        }
81
    }
82
83
    /** @see java.lang.Object#hashCode() */
84
    public int hashCode() {
85
        return toString().hashCode();
86
    }
87
88
    /** @see java.lang.Object#toString() */
89
    public String toString() {
90
        return getResourceSpecification();
91
    }
64
}
92
}
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/ps/PSFontUtils.java (+18 lines)
Lines 112-116 Link Here
112
        gen.writeln("] def");
112
        gen.writeln("] def");
113
    }
113
    }
114
114
115
    /**
116
     * Redefines the encoding of a font.
117
     * @param gen the PostScript generator
118
     * @param fontName the font name
119
     * @param encoding the new encoding (must be predefined in the PS file)
120
     * @throws IOException In case of an I/O problem
121
     */
122
    public static void redefineFontEncoding(PSGenerator gen, String fontName, String encoding) 
123
                throws IOException {
124
        gen.writeln("/" + fontName + " findfont");
125
        gen.writeln("dup length dict begin");
126
        gen.writeln("  {1 index /FID ne {def} {pop pop} ifelse} forall");
127
        gen.writeln("  /Encoding " + encoding + " def");
128
        gen.writeln("  currentdict");
129
        gen.writeln("end");
130
        gen.writeln("/" + fontName + " exch definefont pop");
131
    }
132
115
    
133
    
116
}
134
}
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/java2d/ps/PSDocumentGraphics2D.java (-6 / +3 lines)
Lines 24-30 Link Here
24
import java.io.IOException;
24
import java.io.IOException;
25
25
26
import org.apache.xmlgraphics.ps.DSCConstants;
26
import org.apache.xmlgraphics.ps.DSCConstants;
27
import org.apache.xmlgraphics.ps.PSGenerator;
28
import org.apache.xmlgraphics.ps.PSProcSets;
27
import org.apache.xmlgraphics.ps.PSProcSets;
29
28
30
/**
29
/**
Lines 88-94 Link Here
88
                        + ": PostScript Generator for Java2D"});
87
                        + ": PostScript Generator for Java2D"});
89
        gen.writeDSCComment(DSCConstants.CREATION_DATE,
88
        gen.writeDSCComment(DSCConstants.CREATION_DATE,
90
                    new Object[] {new java.util.Date()});
89
                    new Object[] {new java.util.Date()});
91
        gen.writeDSCComment(DSCConstants.PAGES, PSGenerator.ATEND);
90
        gen.writeDSCComment(DSCConstants.PAGES, DSCConstants.ATEND);
92
        gen.writeDSCComment(DSCConstants.BBOX, new Object[]
91
        gen.writeDSCComment(DSCConstants.BBOX, new Object[]
93
                {ZERO, ZERO, pagewidth, pageheight});
92
                {ZERO, ZERO, pagewidth, pageheight});
94
        gen.writeDSCComment(DSCConstants.END_COMMENTS);
93
        gen.writeDSCComment(DSCConstants.END_COMMENTS);
Lines 103-110 Link Here
103
        
102
        
104
        //Setup
103
        //Setup
105
        gen.writeDSCComment(DSCConstants.BEGIN_SETUP);
104
        gen.writeDSCComment(DSCConstants.BEGIN_SETUP);
106
        PSProcSets.writeFOPStdProcSet(gen);
105
        PSProcSets.writeStdProcSet(gen);
107
        PSProcSets.writeFOPEPSProcSet(gen);
106
        PSProcSets.writeEPSProcSet(gen);
108
        if (customTextHandler != null) {
107
        if (customTextHandler != null) {
109
            customTextHandler.writeSetup();
108
            customTextHandler.writeSetup();
110
        }
109
        }
Lines 129-136 Link Here
129
    
128
    
130
    protected void writePageTrailer() throws IOException {
129
    protected void writePageTrailer() throws IOException {
131
        gen.writeln("showpage");        
130
        gen.writeln("showpage");        
132
        gen.writeDSCComment(DSCConstants.PAGE_TRAILER);
133
        gen.writeDSCComment(DSCConstants.END_PAGE);
134
    }
131
    }
135
    
132
    
136
    /**
133
    /**
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/java/org/apache/xmlgraphics/java2d/ps/EPSDocumentGraphics2D.java (-5 / +4 lines)
Lines 60-66 Link Here
60
                        + ": EPS Generator for Java2D"});
60
                        + ": EPS Generator for Java2D"});
61
        gen.writeDSCComment(DSCConstants.CREATION_DATE, 
61
        gen.writeDSCComment(DSCConstants.CREATION_DATE, 
62
                    new Object[] {new java.util.Date()});
62
                    new Object[] {new java.util.Date()});
63
        gen.writeDSCComment(DSCConstants.PAGES, new Integer(0));
63
        gen.writeDSCComment(DSCConstants.PAGES, DSCConstants.ATEND);
64
        gen.writeDSCComment(DSCConstants.BBOX, new Object[]
64
        gen.writeDSCComment(DSCConstants.BBOX, new Object[]
65
                {ZERO, ZERO, pagewidth, pageheight});
65
                {ZERO, ZERO, pagewidth, pageheight});
66
        gen.writeDSCComment(DSCConstants.LANGUAGE_LEVEL, new Integer(gen.getPSLevel()));
66
        gen.writeDSCComment(DSCConstants.LANGUAGE_LEVEL, new Integer(gen.getPSLevel()));
Lines 68-75 Link Here
68
        
68
        
69
        //Prolog
69
        //Prolog
70
        gen.writeDSCComment(DSCConstants.BEGIN_PROLOG);
70
        gen.writeDSCComment(DSCConstants.BEGIN_PROLOG);
71
        PSProcSets.writeFOPStdProcSet(gen);
71
        PSProcSets.writeStdProcSet(gen);
72
        PSProcSets.writeFOPEPSProcSet(gen);
72
        PSProcSets.writeEPSProcSet(gen);
73
        if (customTextHandler != null) {
73
        if (customTextHandler != null) {
74
            customTextHandler.writeSetup();
74
            customTextHandler.writeSetup();
75
        }
75
        }
Lines 89-96 Link Here
89
    }
89
    }
90
    
90
    
91
    protected void writePageTrailer() throws IOException {
91
    protected void writePageTrailer() throws IOException {
92
        gen.writeDSCComment(DSCConstants.PAGE_TRAILER);
92
        //nop, no DSC PageTrailer needed
93
        gen.writeDSCComment(DSCConstants.END_PAGE);
94
    }
93
    }
95
94
96
}
95
}
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/documentation/content/xdocs/site.xml (+3 lines)
Lines 35-40 Link Here
35
  <about label="XML Graphics Commons">
35
  <about label="XML Graphics Commons">
36
    <index label="Overview" href="index.html" description="Overview"/>
36
    <index label="Overview" href="index.html" description="Overview"/>
37
    <download label="Download" href="download.html" description="Download"/>
37
    <download label="Download" href="download.html" description="Download"/>
38
    <documentation label="Documentation">
39
      <postscript label="Tools for Adobe PostScript" href="postscript.html" description="Tools for Adobe PostScript"/>
40
    </documentation>
38
    <information label="Information">
41
    <information label="Information">
39
      <mail label="Mailing Lists" href="http://xmlgraphics.apache.org/mail.html" description="Information on Mailing Lists"/>
42
      <mail label="Mailing Lists" href="http://xmlgraphics.apache.org/mail.html" description="Information on Mailing Lists"/>
40
      <repo label="Code Repositories" href="http://xmlgraphics.apache.org/repo.html" description="Information on Code Repositories"/>
43
      <repo label="Code Repositories" href="http://xmlgraphics.apache.org/repo.html" description="Information on Code Repositories"/>
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/documentation/content/xdocs/index.xml (+7 lines)
Lines 81-86 Link Here
81
          <td>FOP</td>
81
          <td>FOP</td>
82
        </tr>
82
        </tr>
83
        <tr>
83
        <tr>
84
          <td>Parser/Processor for DSC-compliant PostScript files (DSC = 
85
            <a href="http://partners.adobe.com/public/developer/en/ps/5001.DSC_Spec.pdf">Document Structuring Conventions</a>)
86
          </td>
87
          <td>org.apache.xmlgraphics.ps.dsc</td>
88
          <td>new</td>
89
        </tr>
90
        <tr>
84
          <td><a href="http://www.adobe.com/products/xmp/index.html">XMP metadata</a> framework</td>
91
          <td><a href="http://www.adobe.com/products/xmp/index.html">XMP metadata</a> framework</td>
85
          <td>org.apache.xmlgraphics.xmp</td>
92
          <td>org.apache.xmlgraphics.xmp</td>
86
          <td>new</td>
93
          <td>new</td>
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/src/documentation/content/xdocs/postscript.xml (+142 lines)
Line 0 Link Here
1
<?xml version="1.0" encoding="UTF-8"?>
2
<!--
3
  Licensed to the Apache Software Foundation (ASF) under one or more
4
  contributor license agreements.  See the NOTICE file distributed with
5
  this work for additional information regarding copyright ownership.
6
  The ASF licenses this file to You under the Apache License, Version 2.0
7
  (the "License"); you may not use this file except in compliance with
8
  the License.  You may obtain a copy of the License at
9
10
      http://www.apache.org/licenses/LICENSE-2.0
11
12
  Unless required by applicable law or agreed to in writing, software
13
  distributed under the License is distributed on an "AS IS" BASIS,
14
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
  See the License for the specific language governing permissions and
16
  limitations under the License.
17
-->
18
<!DOCTYPE document PUBLIC "-//APACHE//DTD Documentation V2.0//EN" "http://forrest.apache.org/dtd/document-v20.dtd">
19
<document> 
20
  <header> 
21
    <title>Tools for Adobe PostScript</title> 
22
  </header>
23
  <body> 
24
    <section id="overview">
25
      <title>Overview</title>
26
      <p>
27
        Apache XML Graphics Commons contains various tools for writing and processing Adobe 
28
        PostScript files. This includes:
29
      </p>
30
      <ul>
31
        <li>A PostScript generator class which helps writing PostScript files from scratch.</li>
32
        <li>Two Graphics2D implementations, one for plain PostScript and one for writing 
33
          Encapsulated PostScript (EPS).</li>
34
        <li>A DSC-parser/processor: Parse, post-process and change DSC-compliant PostScript files.</li>
35
      </ul>
36
      <note>
37
        We don't currently include a PostScript interpreter though we would love to have one. A
38
        Java-based PostScript interpreter to keep an eye on is the one from the
39
        <a href="http://foray.sourceforge.net">FOray project</a>.
40
      </note>
41
    </section>
42
    <section id="generator">
43
      <title>The PostScript generator</title>
44
      <p>
45
        The "PSGenerator" class can help writing PostScript files. It deals with things like
46
        escaping, saving/tracking/restoring graphics state, writing DSC comments and tracking of
47
        DSC resources.        
48
      </p>
49
      <p>
50
        You will rarely interact with the PS generator itself, as it is probably more interesting
51
        to generate a PostScript file using Java2D which is described in the following section.
52
      </p>
53
    </section>
54
    <section id="java2d">
55
      <title>Java2D: Graphics2D implementation for generating PostScript and EPS</title>
56
      <p>
57
        We provide two classes (PSDocumentGraphics2D and EPSDocumentGraphics2D) which you can use
58
        to generated complete PostScript files using normal Java2D means. The difference between
59
        the two classes is that the EPS variant creates a fully compliant Encapsulated
60
        PostScript file while the PS variant simply creates a normal DSC-compliant level 2 
61
        PostScript file. It depends on your requirement which variant you choose. The PS variant
62
        is mostly for printing purposes while the EPS variant is better suited for inclusion in
63
        other documents.
64
      </p>
65
      <section id="creating-eps">
66
        <title>Creating an EPS file</title>
67
        <p>
68
          Creating an EPS file using the Graphics2D implementation is easy. Instantiate
69
          EPSDocumentGraphics2D, set a GraphicContext and set up the output document. Here's an
70
          example:
71
        </p>
72
        <source><![CDATA[
73
import org.apache.xmlgraphics.java2d.ps.EPSDocumentGraphics2D;
74
75
[..]
76
77
EPSDocumentGraphics2D g2d = new EPSDocumentGraphics2D(false);
78
g2d.setGraphicContext(new org.apache.xmlgraphics.java2d.GraphicContext());
79
80
//Set up the document size
81
g2d.setupDocument(out, 400, 200); //400pt x 200pt
82
//out is the OutputStream to write the EPS to
83
          
84
g2d.drawRect(10, 10, 50, 50); //paint a rectangle using normal Java2D calls
85
          
86
g2d.finish(); //Wrap up and finalize the EPS file
87
        ]]></source>
88
        <p>
89
          A complete example for generating an EPS files can be found in the 
90
          <a href="http://svn.apache.org/viewvc/xmlgraphics/commons/trunk/examples/java/java2d/ps/">"examples" directory</a>
91
          in the distribution.
92
        </p>
93
      </section>
94
    </section>
95
    <section id="dsc">
96
      <title>DSC parser/processor</title>
97
      <p>
98
        Many PostScript files use special comments to structure a document. This allows manipulation
99
        of PostScript files without interpreting them. These special comments are defined in the
100
        <a href="http://partners.adobe.com/public/developer/en/ps/5001.DSC_Spec.pdf">Document Structuring Conventions</a>.
101
        The code in Commons is designed to work with DSC 3.0. For details on how DSC is used,
102
        please take a look at the DSC specification.
103
      </p>
104
      <p>
105
        The DSC support in Commons was primarily developed to implement resource optimization
106
        features in <a href="ext:fop">Apache FOP</a>'s PostScript output support. Resources like
107
        images which are used repeatedly in a document should not be written to the PostScript
108
        file each time it is used. Instead it is written once at the beginning of the file as a 
109
        PostScript form. The form is then called whenever the image needs painting. 
110
      </p>
111
      <p>
112
        But the DSC parser could potentially be used for other purposes. The most obvious is
113
        extracting a subset of pages from a DSC-compliant file. Assume you want to print only
114
        page 45 to 57 of a particular document. There's an example that demonstrates exactly this.
115
        Check out the "examples" directory in the distribution. Other potential use cases for the 
116
        DSC parser are:
117
      </p>
118
      <ul>
119
        <li>Patching PostScript files, for example, adding OMR marks for automatic packaging</li>
120
        <li><a href="http://en.wikipedia.org/wiki/Imposition">Imposition</a> (2-up, n-up, rotation, etc.)</li>
121
        <li>EPS graphic extraction</li>
122
        <li>Inspecting the page count</li>
123
        <li>etc. etc.</li>
124
      </ul>
125
      <p>
126
        The DSC parser (DSCParser) was designed as a pull parser, i.e. you fetch new events from 
127
        the parser inspecting them and acting on them as they are found. If you prefer to work 
128
        with a push parser, you can pass the DSCParser a DSCHandler implementation and the parser
129
        will send you all the events.
130
      </p>
131
      <p>
132
        The best example to understand how to use the DSC parser is the PageExtractor class
133
        that implements the page extraction functionality mentioned above.
134
      </p>
135
      <note>
136
        The DSC parser is not considered feature-complete. The basic infrastructure is there but,
137
        for example, not all DSC comments are available as concrete Java classes. If you need
138
        to extend the DSC parser for your own use cases, please send us your patches.
139
      </note>
140
    </section>
141
  </body>
142
</document>
0
  + Id
143
  + Id
1
  + native
144
  + native
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/examples/java/ps/DSCProcessingExample1.java (+89 lines)
Line 0 Link Here
1
/*
2
 * Licensed to the Apache Software Foundation (ASF) under one or more
3
 * contributor license agreements.  See the NOTICE file distributed with
4
 * this work for additional information regarding copyright ownership.
5
 * The ASF licenses this file to You under the Apache License, Version 2.0
6
 * (the "License"); you may not use this file except in compliance with
7
 * the License.  You may obtain a copy of the License at
8
 * 
9
 *      http://www.apache.org/licenses/LICENSE-2.0
10
 * 
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
18
/* $Id$ */
19
20
package ps;
21
22
import java.io.File;
23
import java.io.IOException;
24
import java.io.OutputStream;
25
import java.io.InputStream;
26
27
import org.apache.commons.io.IOUtils;
28
import org.apache.xmlgraphics.ps.dsc.DSCException;
29
import org.apache.xmlgraphics.ps.dsc.tools.PageExtractor;
30
 
31
public class DSCProcessingExample1 {
32
33
    public void extractPages(File srcFile, File tgtFile, int from, int to) throws IOException {
34
        InputStream in = new java.io.FileInputStream(srcFile);
35
        in = new java.io.BufferedInputStream(in);
36
        try {
37
            OutputStream out = new java.io.FileOutputStream(tgtFile);
38
            out = new java.io.BufferedOutputStream(out);
39
            try {
40
                PageExtractor.extractPages(in, out, from, to);
41
            } catch (DSCException e) {
42
                throw new RuntimeException(e.getMessage());
43
            } finally {
44
                IOUtils.closeQuietly(out);
45
            }
46
        } finally {
47
            IOUtils.closeQuietly(in);
48
        }
49
        
50
    }
51
    
52
    private static void showInfo() {
53
        System.out.println(
54
                "Call: DSCProcessingExample1 <source-file> <target-file> <from-page> <to-page>");
55
    }
56
    
57
    /**
58
     * Command-line interface
59
     * @param args command-line arguments
60
     */
61
    public static void main(String[] args) {
62
        try {
63
            File srcFile , tgtFile;
64
            int from, to;
65
            if (args.length >= 4) {
66
                srcFile = new File(args[0]);
67
                tgtFile = new File(args[1]);
68
                from = Integer.parseInt(args[2]);
69
                to = Integer.parseInt(args[3]);
70
            } else {
71
                throw new IllegalArgumentException("Invalid number of parameters!");
72
            }
73
            if (!srcFile.exists()) {
74
                throw new IllegalArgumentException("Source file not found: " + srcFile);
75
            }
76
            DSCProcessingExample1 app = new DSCProcessingExample1();
77
            app.extractPages(srcFile, tgtFile, from, to);
78
            System.out.println("File written: " + tgtFile.getCanonicalPath());
79
        } catch (IllegalArgumentException iae) {
80
            System.err.println(iae.getMessage());
81
            showInfo();
82
            System.exit(1);
83
        } catch (Exception e) {
84
            e.printStackTrace();
85
            System.exit(-1);
86
        }
87
    }
88
89
}
0
  + native
90
  + native
(-)C:/Dev/apache.org/rw/xmlgraphics-commons-trunk/examples/java/java2d/ps/EPSExample1.java (-26 / +52 lines)
Lines 22-30 Link Here
22
import java.awt.Color;
22
import java.awt.Color;
23
import java.awt.Font;
23
import java.awt.Font;
24
import java.awt.Graphics2D;
24
import java.awt.Graphics2D;
25
import java.awt.font.TextAttribute;
25
import java.io.File;
26
import java.io.File;
26
import java.io.IOException;
27
import java.io.IOException;
27
import java.io.OutputStream;
28
import java.io.OutputStream;
29
import java.text.AttributedString;
28
30
29
import org.apache.commons.io.IOUtils;
31
import org.apache.commons.io.IOUtils;
30
import org.apache.xmlgraphics.java2d.ps.EPSDocumentGraphics2D;
32
import org.apache.xmlgraphics.java2d.ps.EPSDocumentGraphics2D;
Lines 36-47 Link Here
36
public class EPSExample1 {
38
public class EPSExample1 {
37
39
38
    /**
40
    /**
41
     * Paints a few things on a Graphics2D instance.
42
     * @param g2d the Graphics2D instance
43
     * @param pageNum a page number
44
     */
45
    public void paintSome(Graphics2D g2d, int pageNum) {
46
        //Paint a bounding box
47
        g2d.drawRect(0, 0, 400, 200);
48
        
49
        //A few rectangles rotated and with different color
50
        Graphics2D copy = (Graphics2D)g2d.create();
51
        int c = 12;
52
        for (int i = 0; i < c; i++) {
53
            float f = ((i + 1) / (float)c);
54
            Color col = new Color(0.0f, 1 - f, 0.0f);
55
            copy.setColor(col);
56
            copy.fillRect(70, 90, 50, 50);
57
            copy.rotate(-2 * Math.PI / (double)c, 70, 90);
58
        }
59
        copy.dispose();
60
        
61
        //Some text
62
        copy = (Graphics2D)g2d.create();
63
        copy.rotate(-0.25);
64
        copy.setColor(Color.RED);
65
        copy.setFont(new Font("sans-serif", Font.PLAIN, 36));
66
        copy.drawString("Hello world!", 140, 140);
67
        copy.setColor(Color.RED.darker());
68
        copy.setFont(new Font("serif", Font.PLAIN, 36));
69
        copy.drawString("Hello world!", 140, 180);
70
        copy.dispose();
71
        
72
        //Try attributed text
73
        AttributedString aString = new AttributedString("This is attributed text.");
74
        aString.addAttribute(TextAttribute.FAMILY, "SansSerif");
75
        aString.addAttribute(TextAttribute.FAMILY, "Serif", 8, 18);
76
        aString.addAttribute(TextAttribute.FOREGROUND, Color.orange, 8, 18);
77
        g2d.drawString(aString.getIterator(), 250, 170);
78
        
79
        g2d.drawString("Page: " + pageNum, 250, 190);
80
    }
81
    
82
    /**
39
     * Creates an EPS file. The contents are painted using a Graphics2D implementation that
83
     * Creates an EPS file. The contents are painted using a Graphics2D implementation that
40
     * generates an EPS file.
84
     * generates an EPS file.
41
     * @param outputFile the target file
85
     * @param outputFile the target file
42
     * @throws IOException In case of an I/O error
86
     * @throws IOException In case of an I/O error
43
     */
87
     */
44
    public static void generateEPSusingJava2D(File outputFile) throws IOException {
88
    public void generateEPSusingJava2D(File outputFile) throws IOException {
45
        OutputStream out = new java.io.FileOutputStream(outputFile);
89
        OutputStream out = new java.io.FileOutputStream(outputFile);
46
        out = new java.io.BufferedOutputStream(out);
90
        out = new java.io.BufferedOutputStream(out);
47
        try {
91
        try {
Lines 52-88 Link Here
52
            //Set up the document size
96
            //Set up the document size
53
            g2d.setupDocument(out, 400, 200); //400pt x 200pt
97
            g2d.setupDocument(out, 400, 200); //400pt x 200pt
54
            
98
            
55
            //Paint a bounding box
99
            //Paint something
56
            g2d.drawRect(0, 0, 400, 200);
100
            paintSome(g2d, 1);
57
            
101
            
58
            //A few rectangles rotated and with different color
59
            Graphics2D copy = (Graphics2D)g2d.create();
60
            int c = 12;
61
            for (int i = 0; i < c; i++) {
62
                float f = ((i + 1) / (float)c);
63
                Color col = new Color(0.0f, 1 - f, 0.0f);
64
                copy.setColor(col);
65
                copy.fillRect(70, 90, 50, 50);
66
                copy.rotate(-2 * Math.PI / (double)c, 70, 90);
67
            }
68
            copy.dispose();
69
            
70
            //Some text
71
            g2d.rotate(-0.25);
72
            g2d.setColor(Color.RED);
73
            g2d.setFont(new Font("sans-serif", Font.PLAIN, 36));
74
            g2d.drawString("Hello world!", 140, 140);
75
            g2d.setColor(Color.RED.darker());
76
            g2d.setFont(new Font("serif", Font.PLAIN, 36));
77
            g2d.drawString("Hello world!", 140, 180);
78
            
79
            //Cleanup
102
            //Cleanup
80
            g2d.finish();
103
            g2d.finish();
81
        } finally {
104
        } finally {
82
            IOUtils.closeQuietly(out);
105
            IOUtils.closeQuietly(out);
83
        }
106
        }
84
    }
107
    }
85
    
108
86
    /**
109
    /**
87
     * Command-line interface
110
     * Command-line interface
88
     * @param args command-line arguments
111
     * @param args command-line arguments
Lines 98-104 Link Here
98
            if (!targetDir.exists()) {
121
            if (!targetDir.exists()) {
99
                System.err.println("Target Directory does not exist: " + targetDir);
122
                System.err.println("Target Directory does not exist: " + targetDir);
100
            }
123
            }
101
            generateEPSusingJava2D(new File(targetDir, "eps-example1.eps"));
124
            File outputFile = new File(targetDir, "eps-example1.eps");
125
            EPSExample1 app = new EPSExample1();
126
            app.generateEPSusingJava2D(outputFile);
127
            System.out.println("File written: " + outputFile.getCanonicalPath());
102
        } catch (Exception e) {
128
        } catch (Exception e) {
103
            e.printStackTrace();
129
            e.printStackTrace();
104
        }
130
        }

Return to bug 41582