aboutsummaryrefslogtreecommitdiffstats
path: root/src/java/org/apache/fop/render/awt/AWTRenderer.java
blob: e6ce03acbe912cdd6bd1603a0fb2fdd627f32872 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
/*
 * Copyright 1999-2004 The Apache Software Foundation.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* $Id$ */

package org.apache.fop.render.awt;

/*
 * originally contributed by
 * Juergen Verwohlt: Juergen.Verwohlt@jCatalog.com,
 * Rainer Steinkuhle: Rainer.Steinkuhle@jCatalog.com,
 * Stanislav Gorkhover: Stanislav.Gorkhover@jCatalog.com
 */

// Java
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.print.PageFormat;
import java.awt.print.Pageable;
import java.awt.print.Printable;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import java.util.Vector;

import org.apache.fop.fonts.FontInfo;
import org.apache.fop.apps.FOPException;
import org.apache.fop.apps.FOUserAgent;
import org.apache.fop.area.Area;
import org.apache.fop.area.Page;
import org.apache.fop.area.PageViewport;
import org.apache.fop.area.RegionViewport;
import org.apache.fop.area.Trait;
import org.apache.fop.area.inline.TextArea;
import org.apache.fop.datatypes.ColorType;
import org.apache.fop.image.FopImage;
import org.apache.fop.image.ImageFactory;
import org.apache.fop.render.AbstractRenderer;
import org.apache.fop.traits.BorderProps;
import org.apache.fop.render.awt.FontMetricsMapper;
import org.apache.fop.render.awt.viewer.PreviewDialog;
import org.apache.fop.render.awt.viewer.Translator;

/**
 * This is FOP's AWT renderer.
 */
public class AWTRenderer extends AbstractRenderer implements Printable, Pageable {

    /** The MIME type for PostScript */
    public static final String MIME_TYPE = "application/awt";

    protected double scaleFactor = 100.0;
    protected int pageNumber = 0;
    private int pageWidth = 0;
    private int pageHeight = 0;
    private Vector pageViewportList = new java.util.Vector();
    private Vector pageList = new java.util.Vector();
    private Vector bufferedImageList = new java.util.Vector();
    private BufferedImage currentPageImage = null;
    
    /** Font configuration */
    protected FontInfo fontInfo;

    /**
     * The resource bundle used for AWT messages.
     */
    protected Translator translator = null;

    private Map fontNames = new java.util.Hashtable();
    private Map fontStyles = new java.util.Hashtable();
    private Color saveColor = null;

    /**
     * The preview dialog frame used for display of the documents.
     * Also used as the AWT Component for FontSetup in generating
     * valid font measures.
     */
    protected PreviewDialog frame;

    public AWTRenderer() {
        translator = new Translator();
    }

    public void setUserAgent(FOUserAgent foUserAgent) {
        super.setUserAgent(foUserAgent);
        userAgent.setRendererOverride(this); // for document regeneration
        createPreviewDialog();
    }

    public FOUserAgent getUserAgent() {
        return userAgent;
    }

    /**
     * @see org.apache.fop.render.Renderer
     */
    public boolean supportsOutOfOrder() {
        return false;
    }

    public Translator getTranslator() {
        return translator;
    }

    public void setupFontInfo(FontInfo inFontInfo) {
        // create a temp Image to test font metrics on
        fontInfo = inFontInfo;
        BufferedImage fontImage =
            new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
        FontSetup.setup(fontInfo, fontImage.createGraphics());
    }

    public int getPageNumber() {
        return pageNumber;
    }

    public void setPageNumber(int aValue) {
        pageNumber = aValue;
    }

    public void setScaleFactor(double newScaleFactor) {
        scaleFactor = newScaleFactor;
    }

    public double getScaleFactor() {
        return scaleFactor;
    }

    public void startRenderer(OutputStream out)
    throws IOException {
        // empty pageViewportList, in case of a reload from PreviewDialog
        pageViewportList.removeAllElements();
        pageList.removeAllElements();
        bufferedImageList.removeAllElements();
        System.out.println("\nRegion Types: 0-Before/Top, 1-Start/Left, 2-Body, 3-End/Right, 4-After/Bottom");
    }

    public void stopRenderer()
    throws IOException {
        frame.setStatus(translator.getString("Status.Show"));
        frame.showPage();
    }

    // Printable Interface
    public PageFormat getPageFormat(int pos) {
        return null;
    }

    public Printable getPrintable(int pos) {
        return null;
    }

    public int getNumberOfPages() {
        return pageViewportList.size();
    }

    public int print(Graphics g, PageFormat format, int pos) {
        return 0;
    }

    private PreviewDialog createPreviewDialog() {
        frame = new PreviewDialog(userAgent);
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosed(WindowEvent we) {
                System.exit(0);
            }
        });

        //Centers the window
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension frameSize = frame.getSize();
        if (frameSize.height > screenSize.height) {
            frameSize.height = screenSize.height;
        }
        if (frameSize.width > screenSize.width) {
            frameSize.width = screenSize.width;
        }
        frame.setLocation((screenSize.width - frameSize.width) / 2,
                          (screenSize.height - frameSize.height) / 2);
        frame.setVisible(true);
        frame.setStatus(translator.getString("Status.Build.FO.tree"));
        return frame;
    }

    /** This method override only stores the PageViewport in a vector.
      * No actual rendering performed -- this is done by getPageImage(pageNum) instead.
      * @param pageViewport the <code>PageViewport</code> object supplied by the Area Tree
      * @see org.apache.fop.render.Renderer
    */
    public void renderPage(PageViewport pageViewport)  throws IOException, FOPException {
        pageViewportList.add(pageViewport);
        pageList.add(pageViewport.getPage().clone());
        bufferedImageList.add(getPageImage(pageViewport));
    }

    public BufferedImage getBufferedPageImage(int pageNum) throws FOPException {
        return (BufferedImage) bufferedImageList.get(pageNum);
    }

    /** Generates a desired page from the renderer's page viewport vector.
     * @param pageNum the 0-based page number to generate
     *  @return the <code>java.awt.image.BufferedImage</code> corresponding to the page
     *  @throws FOPException in case of an out-of-range page number requested
    */
    public BufferedImage getPageImage(PageViewport pageViewport) throws FOPException {
        Page page = pageViewport.getPage();

        Rectangle2D bounds = pageViewport.getViewArea();
        pageWidth = (int) Math.round(bounds.getWidth() / 1000f );
        pageHeight = (int) Math.round(bounds.getHeight() / 1000f );
/*
        System.out.println("(Page) X, Y, Width, Height: " + bounds.getX()
            + " " + bounds.getY()
            + " " + bounds.getWidth()
            + " " + bounds.getHeight());
*/
        currentPageImage =
            new BufferedImage((int)((pageWidth * (int)scaleFactor) / 100),
                              (int)((pageHeight * (int)scaleFactor) / 100),
                              BufferedImage.TYPE_INT_RGB);

        Graphics2D graphics = currentPageImage.createGraphics();
        graphics.setRenderingHint (RenderingHints.KEY_FRACTIONALMETRICS,
                                   RenderingHints.VALUE_FRACTIONALMETRICS_ON);

        // transform page based on scale factor supplied
        AffineTransform at = graphics.getTransform();
        at.scale(scaleFactor / 100.0, scaleFactor / 100.0);
        graphics.setTransform(at);

        // draw page frame
        graphics.setColor(Color.white);
        graphics.fillRect(0, 0, pageWidth, pageHeight);
        graphics.setColor(Color.black);
        graphics.drawRect(-1, -1, pageWidth + 2, pageHeight + 2);
        graphics.drawLine(pageWidth + 2, 0, pageWidth + 2, pageHeight + 2);
        graphics.drawLine(pageWidth + 3, 1, pageWidth + 3, pageHeight + 3);
        graphics.drawLine(0, pageHeight + 2, pageWidth + 2, pageHeight + 2);
        graphics.drawLine(1, pageHeight + 3, pageWidth + 3, pageHeight + 3);

        renderPageAreas(page);
        return currentPageImage;
    }

        /** Generates a desired page from the renderer's page viewport vector.
     * @param pageNum the 0-based page number to generate
     *  @return the <code>java.awt.image.BufferedImage</code> corresponding to the page
     *  @throws FOPException in case of an out-of-range page number requested
    */
    public BufferedImage getPageImage(int pageNum) throws FOPException {
        if (pageNum < 0 || pageNum >= pageViewportList.size()) {
            throw new FOPException("out-of-range page number (" + pageNum
                + ") requested; only " + pageViewportList.size()
                + " page(s) available.");
        }
        PageViewport pageViewport = (PageViewport) pageViewportList.get(pageNum);
        Page page = (Page) pageList.get(pageNum);

        Rectangle2D bounds = pageViewport.getViewArea();
        pageWidth = (int) Math.round(bounds.getWidth() / 1000f );
        pageHeight = (int) Math.round(bounds.getHeight() / 1000f );
/*
        System.out.println("(Page) X, Y, Width, Height: " + bounds.getX()
            + " " + bounds.getY()
            + " " + bounds.getWidth()
            + " " + bounds.getHeight());
*/
        currentPageImage =
            new BufferedImage((int)((pageWidth * (int)scaleFactor) / 100),
                              (int)((pageHeight * (int)scaleFactor) / 100),
                              BufferedImage.TYPE_INT_RGB);

        Graphics2D graphics = currentPageImage.createGraphics();
        graphics.setRenderingHint (RenderingHints.KEY_FRACTIONALMETRICS,
                                   RenderingHints.VALUE_FRACTIONALMETRICS_ON);

        // transform page based on scale factor supplied
        AffineTransform at = graphics.getTransform();
        at.scale(scaleFactor / 100.0, scaleFactor / 100.0);
        graphics.setTransform(at);

        // draw page frame
        graphics.setColor(Color.white);
        graphics.fillRect(0, 0, pageWidth, pageHeight);
        graphics.setColor(Color.black);
        graphics.drawRect(-1, -1, pageWidth + 2, pageHeight + 2);
        graphics.drawLine(pageWidth + 2, 0, pageWidth + 2, pageHeight + 2);
        graphics.drawLine(pageWidth + 3, 1, pageWidth + 3, pageHeight + 3);
        graphics.drawLine(0, pageHeight + 2, pageWidth + 2, pageHeight + 2);
        graphics.drawLine(1, pageHeight + 3, pageWidth + 3, pageHeight + 3);

        renderPageAreas(page);
        return currentPageImage;
    }

    /**
     * Handle the traits for a region
     * This is used to draw the traits for the given page region.
     * (See Sect. 6.4.1.2 of XSL-FO spec.)
     * @param region the RegionViewport whose region is to be drawn
     */
    protected void handleRegionTraits(RegionViewport region) {
        Rectangle2D viewArea = region.getViewArea();

        int startX = (int) Math.round((viewArea.getX() / 1000f)
            * (scaleFactor / 100f));
        int startY = (int) Math.round((viewArea.getY() / 1000f)
            * (scaleFactor / 100f));
        // for rounding to work correctly, need to take into account
        // fractional portion of X and Y.
        int width = (int) Math.round(((viewArea.getX() + viewArea.getWidth()) / 1000f)
            * (scaleFactor / 100f)) - startX;
        int height = (int) Math.round(((viewArea.getY() + viewArea.getHeight()) / 1000f)
            * (scaleFactor / 100f)) - startY;

        if (region.getRegion() != null) {
            System.out.print("\nRegion type = " + region.getRegion().getRegionClass());
        }

        System.out.println("  X, Width, Y, Height: " + startX
            + " " + width
            + " " + startY
            + " " + height
            );

        drawBackAndBorders(region, startX, startY, width, height);
    }

    /**
     * Draw the background and borders.
     * This draws the background and border traits for an area given
     * the position.
     *
     * @param block the area to get the traits from
     * @param startx the start x position
     * @param starty the start y position
     * @param width the width of the area
     * @param height the height of the area
     */
    protected void drawBackAndBorders(Area block,
                    int startx, int starty,
                    int width, int height) {

        // draw background then border
        Graphics2D graphics = currentPageImage.createGraphics();
        Trait.Background back;
        back = (Trait.Background) block.getTrait(Trait.BACKGROUND);
        if (back != null) {

            if (back.getColor() != null) {
                graphics.setColor(back.getColor().getAWTColor());
                graphics.fillRect(startx, starty, width, height);
            }
            if (back.getURL() != null) {  // TODO: implement
                ImageFactory fact = ImageFactory.getInstance();
                FopImage fopimage = fact.getImage(back.getURL(), userAgent);
                if (fopimage != null && fopimage.load(FopImage.DIMENSIONS)) {
                    if (back.getRepeat() == BackgroundRepeat.REPEAT) {
                        // create a pattern for the image
                    } else {
                        // place once
                        Rectangle2D pos;
                        pos = new Rectangle2D.Float((startx + back.getHoriz()) * 1000,
                                                    (starty + back.getVertical()) * 1000,
                                                    fopimage.getWidth() * 1000,
                                                    fopimage.getHeight() * 1000);
//                      putImage(back.getURL(), pos);
                    }
                }
            }
        }

        BorderProps bps = (BorderProps) block.getTrait(Trait.BORDER_BEFORE);
        if (bps != null) {
            int borderWidth = (int) Math.round((bps.width / 1000f) * (scaleFactor / 100f));
            graphics.setColor(bps.color.getAWTColor());
            graphics.fillRect(startx, starty, width, borderWidth);
        }
        bps = (BorderProps) block.getTrait(Trait.BORDER_AFTER);
        if (bps != null) {
            int borderWidth = (int) Math.round((bps.width / 1000f) * (scaleFactor / 100f));
            int sy = starty + height;
            graphics.setColor(bps.color.getAWTColor());
            graphics.fillRect(startx, starty + height - borderWidth, 
                width, borderWidth);
        }
        bps = (BorderProps) block.getTrait(Trait.BORDER_START);
        if (bps != null) {
            int borderWidth = (int) Math.round((bps.width / 1000f) * (scaleFactor / 100f));
            graphics.setColor(bps.color.getAWTColor());
            graphics.fillRect(startx, starty, borderWidth, height);
        }
        bps = (BorderProps) block.getTrait(Trait.BORDER_END);
        if (bps != null) {
            int borderWidth = (int) Math.round((bps.width / 1000f) * (scaleFactor / 100f));
            int sx = startx + width;
            graphics.setColor(bps.color.getAWTColor());
            graphics.fillRect(startx + width - borderWidth, starty, 
                borderWidth, height);
        }
        
    }
    
    /**
     * @see org.apache.fop.render.Renderer#renderText(TextArea)
     */
    public void renderText(TextArea text) {
        System.out.println("In render text: " + text.getTextArea());

        Graphics2D graphics = currentPageImage.createGraphics();
        String fontName = (String) text.getTrait(Trait.FONT_NAME);
        int size = ((Integer) text.getTrait(Trait.FONT_SIZE)).intValue();
//      Typeface f = (Typeface) fontInfo.getFonts().get(fontName);
        ColorType ct = (ColorType) text.getTrait(Trait.COLOR);

        FontMetricsMapper mapper = (FontMetricsMapper) 
            fontInfo.getMetricsFor(fontName);
        if (mapper == null) {
            mapper = new FontMetricsMapper("MonoSpaced", java.awt.Font.PLAIN,
                graphics);
        }

//      graphics.setColor(ct.getAWTColor());
//      graphics.setFont(mapper.getFont(size));
        graphics.setColor(java.awt.Color.black);
        graphics.setFont(new java.awt.Font("monospaced", java.awt.Font.PLAIN,
            10));
        
        int rx = currentIPPosition;
        int bl = currentBPPosition + text.getOffset();

        int newx = (int) (rx + 500) / 1000;
        int newy = (int) (pageHeight - (bl + 500) / 1000);
                
        String s = text.getTextArea();
//      graphics.drawString(s, newx, newy);
        graphics.drawString(s, 220, 200);

        // TODO: render text decorations
        currentIPPosition += text.getAllocIPD();
    }

    /** @see org.apache.fop.render.AbstractRenderer */
    public String getMimeType() {
        return MIME_TYPE;
    }

}