aboutsummaryrefslogtreecommitdiffstats
path: root/src/java/org/apache/fop/render/txt/TXTRenderer.java
blob: 85d3dd797863287528c4ec09ca06069d0a9b6bf6 (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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.txt;

import java.awt.Color;
import java.awt.Point;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.fop.apps.FOPException;
import org.apache.fop.area.Area;
import org.apache.fop.area.CTM;
import org.apache.fop.area.PageViewport;
import org.apache.fop.area.inline.Image;
import org.apache.fop.area.inline.TextArea;
import org.apache.fop.render.AbstractPathOrientedRenderer;
import org.apache.fop.render.txt.border.AbstractBorderElement;
import org.apache.fop.render.txt.border.BorderManager;

/**
 * Renderer that renders areas to plain text.
 * 
 * @author Art Welch
 * @author <a href="mailto:mark-fop@inomial.com">Mark Lillywhite</a> (to use
 *         the new Renderer interface)
 */
public class TXTRenderer extends AbstractPathOrientedRenderer {
    
    private static final char LIGHT_SHADE = '\u2591';
    
    private static final char MEDIUM_SHADE = '\u2592';
    
    private static final char DARK_SHADE = '\u2593';

    private static final char FULL_BLOCK = '\u2588';

    private static final char IMAGE_CHAR = '#';

    /**The stream for output */
    private OutputStream outputStream;

    /** The current stream to add Text commands to. */
    private TXTStream currentStream;

    /** Buffer for text. */
    private StringBuffer[] charData;

    /** Buffer for background and images. */
    private StringBuffer[] decoData;

    /** Height of one symbol in Courier font size of 10pt. */
    public static final int CHAR_HEIGHT = 7860;

    /** Width of one symbol in Courier font size of 10pt. */
    public static final int CHAR_WIDTH = 6000;

    /** Current processing page width. */
    private int pageWidth;

    /** Current processing page height. */
    private int pageHeight;

    /**
     * Every line except the last line on a page (which will end with
     * pageEnding) will be terminated with this string.
     */
    private String lineEnding = "\r\n";

    /** Every page except the last one will end with this string. */
    private String pageEnding = "\f";

    /** Equals true, if current page is first. */
    private boolean firstPage = false;

    /** Manager for storing border's information. */
    private BorderManager bm;
    
    /** Char for current filling. */
    private char fillChar;

    /** Saves current coordinate transformation. */
    private TXTState currentState = new TXTState();

    private String encoding;
    
    /**
     * Constructs a newly allocated <code>TXTRenderer</code> object.
     */
    public TXTRenderer() {
    }

    /** @see org.apache.fop.render.AbstractRenderer#getMimeType() */
    public String getMimeType() {
        return "text/plain";
    }

    /** @see org.apache.fop.render.AbstractRenderer */
    public void configure(Configuration conf) throws ConfigurationException {
        super.configure(conf);
        this.encoding = conf.getChild("encoding", true).getValue(null);
    }
    
    /**
     * Sets the encoding of the target file.
     * @param encoding the encoding, null to select the default encoding (UTF-8)
     */
    public void setEncoding(String encoding) {
        this.encoding = encoding;
    }

    /**
     * Indicates if point (x, y) lay inside currentPage.
     * 
     * @param x x coordinate
     * @param y y coordinate
     * @return <b>true</b> if point lay inside page
     */
    public boolean isLayInside(int x, int y) {
        return (x >= 0) && (x < pageWidth) && (y >= 0) && (y < pageHeight);
    }

    /**
     * Add char to text buffer.
     * 
     * @param x  x coordinate
     * @param y  y coordinate
     * @param ch  char to add
     * @param ischar boolean, repersenting is character adding to text buffer
     */
    protected void addChar(int x, int y, char ch, boolean ischar) {
        Point point = currentState.transformPoint(x, y);
        putChar(point.x, point.y, ch, ischar);
    }

    /**
     * Add char to text or background buffer.
     * 
     * @param x x coordinate
     * @param y x coordinate
     * @param ch char to add
     * @param ischar indicates if it char or background
     */
    protected void putChar(int x, int y, char ch, boolean ischar) {
        if (isLayInside(x, y)) {
            StringBuffer sb = ischar ? charData[y] : decoData[y];
            while (sb.length() <= x) {
                sb.append(' ');
            }
            sb.setCharAt(x, ch);
        }
    }

    /**
     * Adds string to text buffer (<code>charData</code>). <p>
     * Chars of string map in turn.
     * 
     * @param row x coordinate
     * @param col y coordinate
     * @param s string to add
     */
    protected void addString(int row, int col, String s) {
        for (int l = 0; l < s.length(); l++) {
            addChar(col + l, row, s.charAt(l), true);
        }
    }

    /**
     * Render TextArea to Text.
     * 
     * @param area  inline area to render
     */
    protected void renderText(TextArea area) {
        int col = Helper.ceilPosition(this.currentIPPosition, CHAR_WIDTH);
        int row = Helper.ceilPosition(this.currentBPPosition, CHAR_HEIGHT);

        String s = area.getText();

        addString(row, col, s);

        super.renderText(area);
    }

    /**
     * @see org.apache.fop.render.Renderer#renderPage(PageViewport)
     */
    public void renderPage(PageViewport page) throws IOException, FOPException {
        if (firstPage) {
            firstPage = false;
        } else {
            currentStream.add(pageEnding);
        }

        Rectangle2D bounds = page.getViewArea();
        double width = bounds.getWidth();
        double height = bounds.getHeight();

        pageWidth = Helper.ceilPosition((int) width, CHAR_WIDTH);
        pageHeight = Helper.ceilPosition((int) height, CHAR_HEIGHT);
        
        // init buffers
        charData = new StringBuffer[pageHeight];
        decoData = new StringBuffer[pageHeight];
        for (int i = 0; i < pageHeight; i++) {
            charData[i] = new StringBuffer();
            decoData[i] = new StringBuffer();
        }

        bm = new BorderManager(pageWidth, pageHeight, currentState);

        super.renderPage(page);

        flushBorderToBuffer();
        flushBuffer();
    }

    /**
     * Projects current page borders (i.e.<code>bm</code>) to buffer for 
     * background and images (i.e.<code>decoData</code>). 
     */
    private void flushBorderToBuffer() {
        for (int x = 0; x < pageWidth; x++) {
            for (int y = 0; y < pageHeight; y++) {
                Character c = bm.getCharacter(x, y);
                if (c != null) {
                    putChar(x, y, c.charValue(), false);
                }
            }
        }
    }

    /**
     * Write out the buffer to output stream.
     */
    private void flushBuffer() {
        for (int row = 0; row < pageHeight; row++) {
            StringBuffer cr = charData[row];
            StringBuffer dr = decoData[row];
            StringBuffer outr = null;

            if (cr != null && dr == null) {
                outr = cr;
            } else if (dr != null && cr == null) {
                outr = dr;
            } else if (cr != null && dr != null) {
                int len = dr.length();
                if (cr.length() > len) {
                    len = cr.length();
                }
                outr = new StringBuffer();
                for (int countr = 0; countr < len; countr++) {
                    if (countr < cr.length() && cr.charAt(countr) != ' ') {
                        outr.append(cr.charAt(countr));
                    } else if (countr < dr.length()) {
                        outr.append(dr.charAt(countr));
                    } else {
                        outr.append(' ');
                    }
                }
            }

            if (outr != null) {
                currentStream.add(outr.toString());
            }
            if (row < pageHeight) {
                currentStream.add(lineEnding);
            }
        }
    }

    /**
     * @see org.apache.fop.render.Renderer#startRenderer(java.io.OutputStream)
     */
    public void startRenderer(OutputStream os) throws IOException {
        log.info("Rendering areas to TEXT.");
        this.outputStream = os;
        currentStream = new TXTStream(os);
        currentStream.setEncoding(this.encoding);
        firstPage = true;
    }

    /**
     * @see org.apache.fop.render.Renderer#stopRenderer()
     */
    public void stopRenderer() throws IOException {
        log.info("writing out TEXT");
        outputStream.flush();
        super.stopRenderer();
    }

    /**
     * Does nothing.
     * @see org.apache.fop.render.AbstractPathOrientedRenderer
     */
    protected void restoreStateStackAfterBreakOut(List breakOutList) {
    }

    /**
     * Does nothing.
     * @return null
     * @see org.apache.fop.render.AbstractPathOrientedRenderer
     */
    protected List breakOutOfStateStack() {
        return null;
    }

    /**
     * Does nothing.
     * @see org.apache.fop.render.AbstractPathOrientedRenderer
     */
    protected void saveGraphicsState() {
    }

    /**
     * Does nothing.
     * @see org.apache.fop.render.AbstractPathOrientedRenderer
     */
    protected void restoreGraphicsState() {
    }

    /**
     * Does nothing.
     * @see org.apache.fop.render.AbstractPathOrientedRenderer
     */
    protected void beginTextObject() {
    }

    /**
     * Does nothing.
     * @see org.apache.fop.render.AbstractPathOrientedRenderer
     */
    protected void endTextObject() {
    }

    /**
     * Does nothing.
     * @see org.apache.fop.render.AbstractPathOrientedRenderer
     */
    protected void clip() {
    }

    /**
     * Does nothing.
     * @see org.apache.fop.render.AbstractPathOrientedRenderer
     */
    protected void clipRect(float x, float y, float width, float height) {
    }

    /**
     * Does nothing. 
     * @see org.apache.fop.render.AbstractPathOrientedRenderer
     */
    protected void moveTo(float x, float y) {
    }

    /**
     * Does nothing. 
     * @see org.apache.fop.render.AbstractPathOrientedRenderer
     */
    protected void lineTo(float x, float y) {
    }

    /**
     * Does nothing.
     * @see org.apache.fop.render.AbstractPathOrientedRenderer
     */
    protected void closePath() {
    }

    /**
     * Fills rectangle startX, startY, width, height with char 
     * <code>charToFill</code>.
     * 
     * @param startX x-coordinate of upper left point
     * @param startY y-coordinate of upper left point
     * @param width width of rectangle
     * @param height height of rectangle
     * @param charToFill filling char 
     */
    private void fillRect(int startX, int startY, int width, int height, 
            char charToFill) {
        for (int x = startX; x < startX + width; x++) {
            for (int y = startY; y < startY + height; y++) {
                addChar(x, y, charToFill, false);
            }
        }
    }
    
    /**
     * Fills a rectangular area with the current filling char.
     * @see org.apache.fop.render.AbstractPathOrientedRenderer
     */
    protected void fillRect(float x, float y, float width, float height) {
        fillRect(bm.getStartX(), bm.getStartY(), bm.getWidth(), bm.getHeight(),
                fillChar);
    }
    
    /**
     * Changes current filling char.
     * @see org.apache.fop.render.AbstractPathOrientedRenderer
     */
    protected void updateColor(Color col, boolean fill) {
        if (col == null) {
            return;
        }
        // fillShade evaluation was taken from fop-0.20.5
        // TODO: This fillShase is catually the luminance component of the color
        // transformed to the YUV (YPrBb) Colorspace. It should use standard
        // Java methods for its conversion instead of the formula given here.
        double fillShade = 0.30f / 255f * col.getRed() 
                         + 0.59f / 255f * col.getGreen() 
                         + 0.11f / 255f * col.getBlue();
        fillShade = 1 - fillShade;
        
        if (fillShade > 0.8f) {
            fillChar = FULL_BLOCK;
        } else if (fillShade > 0.6f) {
            fillChar = DARK_SHADE;
        } else if (fillShade > 0.4f) {
            fillChar = MEDIUM_SHADE;
        } else if (fillShade > 0.2f) {
            fillChar = LIGHT_SHADE;
        } else {
            fillChar = ' ';
        }
    }

    /**
     * @see org.apache.fop.render.AbstractPathOrientedRenderer#drawImage(
     *          java.lang.String, java.awt.geom.Rectangle2D, java.util.Map)
     */
    protected void drawImage(String url, Rectangle2D pos, Map foreignAttributes) {
        //No images are painted here
    }
    
    /**
     * Fills image rectangle with a <code>IMAGE_CHAR</code>.
     * @see org.apache.fop.render.AbstractPathOrientedRenderer
     */
    public void renderImage(Image image, Rectangle2D pos) {
        int x1 = Helper.ceilPosition(currentIPPosition, CHAR_WIDTH);
        int y1 = Helper.ceilPosition(currentBPPosition, CHAR_HEIGHT);
        int width = Helper.ceilPosition((int) pos.getWidth(), CHAR_WIDTH);
        int height = Helper.ceilPosition((int) pos.getHeight(), CHAR_HEIGHT);
        
        fillRect(x1, y1, width, height, IMAGE_CHAR);
    }

    
    /**
     * Returns the closest integer to the multiplication of a number and 1000.
     * 
     * @param x  the value of the argument, multiplied by 
     *            1000 and rounded
     * @return the value of the argument multiplied by 
     *         1000 and rounded to the nearest integer
     */
    protected int toMilli(float x) {
        return Math.round(x * 1000f);
    }

    /**
     * Adds one element of border.
     * 
     * @param x  x coordinate
     * @param y  y coordinate
     * @param style  integer, representing border style
     * @param type  integer, representing border element type 
     */
    private void addBitOfBorder(int x, int y, int style, int type) {
        Point point = currentState.transformPoint(x, y);
        if (isLayInside(point.x, point.y)) {
            bm.addBorderElement(point.x, point.y, style, type);
        }
    }

    /**
     * @see org.apache.fop.render.AbstractPathOrientedRenderer
     */
    protected void drawBorderLine(float x1, float y1, float x2, float y2,
            boolean horz, boolean startOrBefore, int style, Color col) {

        int borderHeight = bm.getHeight();
        int borderWidth = bm.getWidth();
        int borderStartX = bm.getStartX();
        int borderStartY = bm.getStartY();

        int x, y;
        if (horz && startOrBefore) { // BEFORE
            x = borderStartX;
            y = borderStartY;
        } else if (horz && !startOrBefore) { // AFTER
            x = borderStartX;
            y = borderStartY + borderHeight - 1;
        } else if (!horz && startOrBefore) { // START
            x = borderStartX;
            y = borderStartY;
        } else { // END
            x = borderStartX + borderWidth - 1;
            y = borderStartY;
        }

        int dx, dy, length, startType, endType;
        if (horz) {
            length = borderWidth;
            dx = 1;
            dy = 0;
            startType = 1 << AbstractBorderElement.RIGHT;
            endType = 1 << AbstractBorderElement.LEFT;
        } else {
            length = borderHeight;
            dx = 0;
            dy = 1;
            startType = 1 << AbstractBorderElement.DOWN;
            endType = 1 << AbstractBorderElement.UP;
        }

        addBitOfBorder(x, y, style, startType);
        for (int i = 0; i < length - 2; i++) {
            x += dx;
            y += dy;
            addBitOfBorder(x, y, style, startType + endType);
        }
        x += dx;
        y += dy;
        addBitOfBorder(x, y, style, endType);
    }

    /**
     * @see org.apache.fop.render.AbstractPathOrientedRenderer 
     */
    protected void drawBackAndBorders(Area area, float startx, float starty,
            float width, float height) {
        bm.setWidth(Helper.ceilPosition(toMilli(width), CHAR_WIDTH));
        bm.setHeight(Helper.ceilPosition(toMilli(height), CHAR_HEIGHT));
        bm.setStartX(Helper.ceilPosition(toMilli(startx), CHAR_WIDTH));
        bm.setStartY(Helper.ceilPosition(toMilli(starty), CHAR_HEIGHT));

        super.drawBackAndBorders(area, startx, starty, width, height);
    }

    /**
     * @see org.apache.fop.render.AbstractRenderer#startVParea(CTM, Rectangle2D)
     */
    protected void startVParea(CTM ctm, Rectangle2D clippingRect) {
        currentState.push(ctm);
    }

    /**
     * @see org.apache.fop.render.AbstractRenderer#endVParea()
     */
    protected void endVParea() {
        currentState.pop();
    }
}