aboutsummaryrefslogtreecommitdiffstats
path: root/src/java/org/apache/fop/render/AbstractPathOrientedRenderer.java
blob: bc514acd9bc24e23a84ecc3df935d6661daa35db (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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
/*
 * 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;

import java.awt.Color;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.util.List;
import java.util.Map;

import org.w3c.dom.Document;

import org.apache.batik.parser.AWTTransformProducer;

import org.apache.xmlgraphics.image.loader.ImageSize;
import org.apache.xmlgraphics.util.QName;
import org.apache.xmlgraphics.util.UnitConv;

import org.apache.fop.apps.FOUserAgent;
import org.apache.fop.area.Area;
import org.apache.fop.area.Block;
import org.apache.fop.area.BlockViewport;
import org.apache.fop.area.CTM;
import org.apache.fop.area.NormalFlow;
import org.apache.fop.area.RegionReference;
import org.apache.fop.area.RegionViewport;
import org.apache.fop.area.Trait;
import org.apache.fop.area.inline.ForeignObject;
import org.apache.fop.area.inline.InlineArea;
import org.apache.fop.area.inline.InlineViewport;
import org.apache.fop.fo.Constants;
import org.apache.fop.fo.extensions.ExtensionElementMapping;
import org.apache.fop.fonts.FontMetrics;
import org.apache.fop.traits.BorderProps;


/**
 * Abstract base class for renderers like PDF and PostScript where many painting operations
 * follow similar patterns which makes it possible to share some code.
 */
public abstract class AbstractPathOrientedRenderer extends PrintRenderer {

    /**
     * @param userAgent the user agent that contains configuration details. This cannot be null.
     */
    public AbstractPathOrientedRenderer(FOUserAgent userAgent) {
        super(userAgent);
    }

    /**
     * Handle block traits.
     * The block could be any sort of block with any positioning
     * so this should render the traits such as border and background
     * in its position.
     *
     * @param block the block to render the traits
     */
    protected void handleBlockTraits(Block block) {
        float borderPaddingStart = block.getBorderAndPaddingWidthStart() / 1000f;
        float borderPaddingEnd = block.getBorderAndPaddingWidthEnd() / 1000f;
        float borderPaddingBefore = block.getBorderAndPaddingWidthBefore() / 1000f;
        float borderPaddingAfter = block.getBorderAndPaddingWidthAfter() / 1000f;

        float startx = currentIPPosition / 1000f;
        float starty = currentBPPosition / 1000f;
        float width = block.getIPD() / 1000f;
        float height = block.getBPD() / 1000f;

        int level = block.getBidiLevel();
        if ((level == -1) || ((level & 1) == 0)) {
            startx += block.getStartIndent() / 1000f;
            startx -= borderPaddingStart;
        } else {
            startx += block.getEndIndent() / 1000f;
            startx -= borderPaddingEnd;
        }

        width += borderPaddingStart;
        width += borderPaddingEnd;
        height += borderPaddingBefore;
        height += borderPaddingAfter;

        drawBackAndBorders(block, startx, starty, width, height);
    }

    /**
     * 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();
        RegionReference referenceArea = region.getRegionReference();
        float startx = (float)(viewArea.getX() / 1000f);
        float starty = (float)(viewArea.getY() / 1000f);
        float width = (float)(viewArea.getWidth() / 1000f);
        float height = (float)(viewArea.getHeight() / 1000f);

        // adjust the current position according to region borders and padding
        currentBPPosition = referenceArea.getBorderAndPaddingWidthBefore();
        int level = region.getBidiLevel();
        if ((level == -1) || ((level & 1) == 0)) {
            currentIPPosition = referenceArea.getBorderAndPaddingWidthStart();
        } else {
            currentIPPosition = referenceArea.getBorderAndPaddingWidthEnd();
        }
        // draw background (traits are in the RegionViewport)
        // and borders (traits are in the RegionReference)
        drawBackAndBorders(region, referenceArea, startx, starty, width, height);
    }

    /**
     * Draw the background and borders.
     * This draws the background and border traits for an area given
     * the position.
     *
     * @param area 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 area,
                    float startx, float starty,
                    float width, float height) {
        drawBackAndBorders(area, area, startx, starty, width, height);
    }

    /**
     * Draw the background and borders.
     * This draws the background and border traits for an area given
     * the position.
     *
     * @param backgroundArea the area to get the background traits from
     * @param borderArea the area to get the border 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 backgroundArea, Area borderArea,
                    float startx, float starty,
                    float width, float height) {
        // draw background then border

        BorderProps bpsBefore = (BorderProps)borderArea.getTrait(Trait.BORDER_BEFORE);
        BorderProps bpsAfter = (BorderProps)borderArea.getTrait(Trait.BORDER_AFTER);
        BorderProps bpsStart = (BorderProps)borderArea.getTrait(Trait.BORDER_START);
        BorderProps bpsEnd = (BorderProps)borderArea.getTrait(Trait.BORDER_END);

        Trait.Background backgroundTrait
            = (Trait.Background)backgroundArea.getTrait(Trait.BACKGROUND);

        drawBackground(startx, starty, width, height,
                (Trait.Background) backgroundArea.getTrait(Trait.BACKGROUND),
                bpsBefore, bpsAfter, bpsStart, bpsEnd, backgroundArea.getBidiLevel());
        // TODO what is the default bg color?   Should we serialize it?
        Color bg = Color.white;
        if (backgroundTrait != null &&  backgroundTrait.getColor() != null) {
            bg = backgroundTrait.getColor();
        }

        drawBorders(startx, starty, width, height,
                bpsBefore, bpsAfter, bpsStart, bpsEnd, backgroundArea.getBidiLevel(), bg);
    }

    /**
     * Draw the background.
     * This draws the background given the position and the traits.
     *
     * @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
     * @param back the background traits
     * @param bpsBefore the border-before traits
     * @param bpsAfter the border-after traits
     * @param bpsStart the border-start traits
     * @param bpsEnd the border-end traits
     * @param level of bidirectional embedding
     */
    protected void drawBackground(float startx, float starty, float width, float height, Trait.Background back,
            BorderProps bpsBefore, BorderProps bpsAfter,
            BorderProps bpsStart, BorderProps bpsEnd, int level) {
        BorderProps bpsTop = bpsBefore;
        BorderProps bpsBottom = bpsAfter;
        BorderProps bpsLeft;
        BorderProps bpsRight;
        if ((level == -1) || ((level & 1) == 0)) {
            bpsLeft = bpsStart;
            bpsRight = bpsEnd;
        } else {
            bpsLeft = bpsEnd;
            bpsRight = bpsStart;
        }
        drawBackground(startx, starty, width, height, back, bpsTop, bpsBottom, bpsLeft, bpsRight);
    }

    /**
     * Draw the background.
     * This draws the background given the position and the traits.
     *
     * @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
     * @param back the background traits
     * @param bpsTop the border specification on the top edge
     * @param bpsBottom the border traits associated with bottom edge
     * @param bpsLeft the border specification on the left edge
     * @param bpsRight the border specification on the right edge
     */
    protected void drawBackground(float startx, float starty, float width, float height, Trait.Background back,
            BorderProps bpsTop, BorderProps bpsBottom,
            BorderProps bpsLeft, BorderProps bpsRight) {
        if (back != null) {
            endTextObject();

            //Calculate padding rectangle
            float sx = startx;
            float sy = starty;
            float paddRectWidth = width;
            float paddRectHeight = height;
            if (bpsLeft != null) {
                sx += bpsLeft.width / 1000f;
                paddRectWidth -= bpsLeft.width / 1000f;
            }
            if (bpsTop != null) {
                sy += bpsTop.width / 1000f;
                paddRectHeight -= bpsTop.width / 1000f;
            }
            if (bpsRight != null) {
                paddRectWidth -= bpsRight.width / 1000f;
            }
            if (bpsBottom != null) {
                paddRectHeight -= bpsBottom.width / 1000f;
            }

            saveGraphicsState();

            clipBackground(sx, sy,  paddRectWidth, paddRectHeight, bpsTop, bpsBottom, bpsLeft, bpsRight);

            if (back.getColor() != null) {
                updateColor(back.getColor(), true);
                fillRect(sx, sy, paddRectWidth, paddRectHeight);
            }

            if (back.getImageInfo() != null) {
                ImageSize imageSize = back.getImageInfo().getSize();
                int targetWidth = imageSize.getWidthMpt();
                int targetHeight = imageSize.getHeightMpt();
                double multiplier = 1.0;
                if (back.getImageTargetWidth() != 0 && back.getImageTargetHeight() != 0) {
                    multiplier = Math.min(1.0 * back.getImageTargetWidth() / targetWidth,
                            1.0 * back.getImageTargetHeight() / targetHeight);
                } else if (back.getImageTargetHeight() != 0) {
                    multiplier = 1.0 * back.getImageTargetHeight() / targetHeight;
                } else if (back.getImageTargetWidth() != 0) {
                    multiplier = 1.0 * back.getImageTargetWidth() / targetWidth;
                }
                targetWidth = (int) (targetWidth * multiplier);
                targetHeight = (int) (targetHeight * multiplier);
                int horzCount = (int) ((paddRectWidth * 1000 / targetWidth) + 1.0f);
                int vertCount = (int) ((paddRectHeight * 1000 / targetHeight) + 1.0f);
                if (back.getRepeat() == EN_NOREPEAT) {
                    horzCount = 1;
                    vertCount = 1;
                } else if (back.getRepeat() == EN_REPEATX) {
                    vertCount = 1;
                } else if (back.getRepeat() == EN_REPEATY) {
                    horzCount = 1;
                }
                //change from points to millipoints
                sx *= 1000;
                sy *= 1000;
                if (horzCount == 1) {
                    sx += back.getHoriz();
                }
                if (vertCount == 1) {
                    sy += back.getVertical();
                }
                for (int x = 0; x < horzCount; x++) {
                    for (int y = 0; y < vertCount; y++) {
                        // place once
                        Rectangle2D pos;
                        // Image positions are relative to the currentIP/BP
                        pos = new Rectangle2D.Float(sx - currentIPPosition + (x * targetWidth), sy
                                - currentBPPosition + (y * targetHeight), targetWidth, targetHeight);
                        drawImage(back.getURL(), pos);
                    }
                }
            }
            restoreGraphicsState();
        }
    }

    /**
     * TODO represent border related parameters in a class
     * Clip the background to the inner border.
     * This draws the border traits given the position and the traits.
     *
     * @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
     * @param bpsBefore the border-before traits
     * @param bpsAfter the border-after traits
     * @param bpsStart the border-start traits
     * @param bpsEnd the border-end traits
     * @param innerBackgroundColor the background color of the block
     */
    protected void clipBackground(float startx, float starty,
            float width, float height,
            BorderProps bpsBefore, BorderProps bpsAfter,
            BorderProps bpsStart, BorderProps bpsEnd) {

        clipRect(startx, starty, width, height);

    }

    /**
     * Draw the borders.
     * This draws the border traits given the position and the traits.
     *
     * @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
     * @param bpsBefore the border traits associated with before edge
     * @param bpsAfter the border traits associated with after edge
     * @param bpsStart the border traits associated with start edge
     * @param bpsEnd the border traits associated with end edge
     * @param level of bidirectional embedding
     * @param innerBackgroundColor the background color of the block
     */
    protected void drawBorders(float startx, float starty, float width, float height,
            BorderProps bpsBefore, BorderProps bpsAfter,
            BorderProps bpsStart, BorderProps bpsEnd, int level, Color innerBackgroundColor) {
        Rectangle2D.Float borderRect = new Rectangle2D.Float(startx, starty, width, height);
        BorderProps bpsTop = bpsBefore;
        BorderProps bpsBottom = bpsAfter;
        BorderProps bpsLeft;
        BorderProps bpsRight;
        if ((level == -1) || ((level & 1) == 0)) {
            bpsLeft = bpsStart;
            bpsRight = bpsEnd;
        } else {
            bpsLeft = bpsEnd;
            bpsRight = bpsStart;
        }
        drawBorders(borderRect, bpsTop, bpsBottom, bpsLeft, bpsRight, innerBackgroundColor);
    }

    private static final int TOP = 0;
    private static final int RIGHT = 1;
    private static final int BOTTOM = 2;
    private static final int LEFT = 3;

    /**
     * Draws borders.
     * @param borderRect the border rectangle
     * @param bpsTop the border specification on the top edge
     * @param bpsBottom the border traits associated with bottom edge
     * @param bpsLeft the border specification on the left edge
     * @param bpsRight the border specification on the right edge
     * @param innerBackgroundColor the background color of the block
     */
    protected void drawBorders(Rectangle2D.Float borderRect,
            BorderProps bpsTop, BorderProps bpsBottom, BorderProps bpsLeft, BorderProps bpsRight,
            Color innerBackgroundColor) {
        //TODO generalize each of the four conditions into using a parameterized drawBorder()
        boolean[] border = new boolean[] {
                (bpsTop != null), (bpsRight != null),
                (bpsBottom != null), (bpsLeft != null)};
        float startx = borderRect.x;
        float starty = borderRect.y;
        float width = borderRect.width;
        float height = borderRect.height;
        float[] borderWidth = new float[] {
            (border[TOP] ? bpsTop.width / 1000f : 0.0f),
            (border[RIGHT] ? bpsRight.width / 1000f : 0.0f),
            (border[BOTTOM] ? bpsBottom.width / 1000f : 0.0f),
            (border[LEFT] ? bpsLeft.width / 1000f : 0.0f)};
        float[] clipw = new float[] {
            BorderProps.getClippedWidth(bpsTop) / 1000f,
            BorderProps.getClippedWidth(bpsRight) / 1000f,
            BorderProps.getClippedWidth(bpsBottom) / 1000f,
            BorderProps.getClippedWidth(bpsLeft) / 1000f};

        starty += clipw[TOP];
        height -= clipw[TOP];
        height -= clipw[BOTTOM];
        startx += clipw[LEFT];
        width -= clipw[LEFT];
        width -= clipw[RIGHT];

        boolean[] slant = new boolean[] {
            (border[LEFT] && border[TOP]),
            (border[TOP] && border[RIGHT]),
            (border[RIGHT] && border[BOTTOM]),
            (border[BOTTOM] && border[LEFT])};
        if (bpsTop != null) {
            endTextObject();

            float sx1 = startx;
            float sx2 = (slant[TOP] ? sx1 + borderWidth[LEFT] - clipw[LEFT] : sx1);
            float ex1 = startx + width;
            float ex2 = (slant[RIGHT] ? ex1 - borderWidth[RIGHT] + clipw[RIGHT] : ex1);
            float outery = starty - clipw[TOP];
            float clipy = outery + clipw[TOP];
            float innery = outery + borderWidth[TOP];

            saveGraphicsState();
            moveTo(sx1, clipy);
            float sx1a = sx1;
            float ex1a = ex1;

            if (isCollapseOuter(bpsTop)) {
                if (isCollapseOuter(bpsLeft)) {
                    sx1a -= clipw[LEFT];
                }
                if (isCollapseOuter(bpsRight)) {
                    ex1a += clipw[RIGHT];
                }
                lineTo(sx1a, outery);
                lineTo(ex1a, outery);
            }
            lineTo(ex1, clipy);
            lineTo(ex2, innery);
            lineTo(sx2, innery);
            closePath();
            clip();
            drawBorderLine(sx1a, outery, ex1a, innery, true, true,
                    bpsTop.style, bpsTop.color);
            restoreGraphicsState();
        }
        if (bpsRight != null) {
            endTextObject();

            float sy1 = starty;
            float sy2 = (slant[RIGHT] ? sy1 + borderWidth[TOP] - clipw[TOP] : sy1);
            float ey1 = starty + height;
            float ey2 = (slant[BOTTOM] ? ey1 - borderWidth[BOTTOM] + clipw[BOTTOM] : ey1);
            float outerx = startx + width + clipw[RIGHT];
            float clipx = outerx - clipw[RIGHT];
            float innerx = outerx - borderWidth[RIGHT];

            saveGraphicsState();
            moveTo(clipx, sy1);
            float sy1a = sy1;
            float ey1a = ey1;
            if (isCollapseOuter(bpsRight)) {
                if (isCollapseOuter(bpsTop)) {
                    sy1a -= clipw[TOP];
                }
                if (isCollapseOuter(bpsBottom)) {
                    ey1a += clipw[BOTTOM];
                }
                lineTo(outerx, sy1a);
                lineTo(outerx, ey1a);
            }
            lineTo(clipx, ey1);
            lineTo(innerx, ey2);
            lineTo(innerx, sy2);
            closePath();
            clip();
            drawBorderLine(innerx, sy1a, outerx, ey1a, false, false,
                           bpsRight.style, bpsRight.color);
            restoreGraphicsState();
        }
        if (bpsBottom != null) {
            endTextObject();

            float sx1 = startx;
            float sx2 = (slant[LEFT] ? sx1 + borderWidth[LEFT] - clipw[LEFT] : sx1);
            float ex1 = startx + width;
            float ex2 = (slant[BOTTOM] ? ex1 - borderWidth[RIGHT] + clipw[RIGHT] : ex1);
            float outery = starty + height + clipw[BOTTOM];
            float clipy = outery - clipw[BOTTOM];
            float innery = outery - borderWidth[BOTTOM];

            saveGraphicsState();
            moveTo(ex1, clipy);
            float sx1a = sx1;
            float ex1a = ex1;
            if (isCollapseOuter(bpsBottom)) {
                if (isCollapseOuter(bpsLeft)) {
                    sx1a -= clipw[LEFT];
                }
                if (isCollapseOuter(bpsRight)) {
                    ex1a += clipw[RIGHT];
                }
                lineTo(ex1a, outery);
                lineTo(sx1a, outery);
            }
            lineTo(sx1, clipy);
            lineTo(sx2, innery);
            lineTo(ex2, innery);
            closePath();
            clip();
            drawBorderLine(sx1a, innery, ex1a, outery, true, false,
                           bpsBottom.style, bpsBottom.color);
            restoreGraphicsState();
        }
        if (bpsLeft != null) {
            endTextObject();

            float sy1 = starty;
            float sy2 = (slant[TOP] ? sy1 + borderWidth[TOP] - clipw[TOP] : sy1);
            float ey1 = sy1 + height;
            float ey2 = (slant[LEFT] ? ey1 - borderWidth[BOTTOM] + clipw[BOTTOM] : ey1);
            float outerx = startx - clipw[LEFT];
            float clipx = outerx + clipw[LEFT];
            float innerx = outerx + borderWidth[LEFT];

            saveGraphicsState();
            moveTo(clipx, ey1);
            float sy1a = sy1;
            float ey1a = ey1;
            if (isCollapseOuter(bpsLeft)) {
                if (isCollapseOuter(bpsTop)) {
                    sy1a -= clipw[TOP];
                }
                if (isCollapseOuter(bpsBottom)) {
                    ey1a += clipw[BOTTOM];
                }
                lineTo(outerx, ey1a);
                lineTo(outerx, sy1a);
            }
            lineTo(clipx, sy1);
            lineTo(innerx, sy2);
            lineTo(innerx, ey2);
            closePath();
            clip();
            drawBorderLine(outerx, sy1a, innerx, ey1a, false, true, bpsLeft.style, bpsLeft.color);
            restoreGraphicsState();
        }
    }

    private boolean isCollapseOuter(BorderProps bp) {
        return bp != null && bp.isCollapseOuter();
    }

    /**
     * Common method to render the background and borders for any inline area.
     * The all borders and padding are drawn outside the specified area.
     * @param area the inline area for which the background, border and padding is to be
     * rendered
     */
    protected void renderInlineAreaBackAndBorders(InlineArea area) {
        float borderPaddingStart = area.getBorderAndPaddingWidthStart() / 1000f;
        float borderPaddingEnd = area.getBorderAndPaddingWidthEnd() / 1000f;
        float borderPaddingBefore = area.getBorderAndPaddingWidthBefore() / 1000f;
        float borderPaddingAfter = area.getBorderAndPaddingWidthAfter() / 1000f;
        float bpwidth = borderPaddingStart + borderPaddingEnd;
        float bpheight = borderPaddingBefore + borderPaddingAfter;

        float height = area.getBPD() / 1000f;
        if (height != 0.0f || bpheight != 0.0f && bpwidth != 0.0f) {
            float x = currentIPPosition / 1000f;
            float y = (currentBPPosition + area.getBlockProgressionOffset()) / 1000f;
            float width = area.getIPD() / 1000f;
            drawBackAndBorders(area, x, y - borderPaddingBefore
                                , width + bpwidth
                                , height + bpheight);
        }
    }

    /** Constant for the fox:transform extension attribute */
    protected static final QName FOX_TRANSFORM
            = new QName(ExtensionElementMapping.URI, "fox:transform");

    /** {@inheritDoc} */
    protected void renderBlockViewport(BlockViewport bv, List children) {
        // clip and position viewport if necessary

        // save positions
        int saveIP = currentIPPosition;
        int saveBP = currentBPPosition;

        CTM ctm = bv.getCTM();
        int borderPaddingBefore = bv.getBorderAndPaddingWidthBefore();

        int positioning = bv.getPositioning();
        if (positioning == Block.ABSOLUTE || positioning == Block.FIXED) {

            //For FIXED, we need to break out of the current viewports to the
            //one established by the page. We save the state stack for restoration
            //after the block-container has been painted. See below.
            List breakOutList = null;
            if (positioning == Block.FIXED) {
                breakOutList = breakOutOfStateStack();
            }

            AffineTransform positionTransform = new AffineTransform();
            positionTransform.translate(bv.getXOffset(), bv.getYOffset());

            int level = bv.getBidiLevel();
            int borderPaddingStart = bv.getBorderAndPaddingWidthStart();
            int borderPaddingEnd = bv.getBorderAndPaddingWidthEnd();

            //"left/"top" (bv.getX/YOffset()) specify the position of the content rectangle
            if ((level == -1) || ((level & 1) == 0)) {
                positionTransform.translate(-borderPaddingStart, -borderPaddingBefore);
            } else {
                positionTransform.translate(-borderPaddingEnd, -borderPaddingBefore);
            }

            //Free transformation for the block-container viewport
            String transf;
            transf = bv.getForeignAttributeValue(FOX_TRANSFORM);
            if (transf != null) {
                AffineTransform freeTransform = AWTTransformProducer.createAffineTransform(transf);
                positionTransform.concatenate(freeTransform);
            }

            //Viewport position
            if (!positionTransform.isIdentity()) {
                establishTransformationMatrix(positionTransform);
            }

            //This is the content-rect
            float width = bv.getIPD() / 1000f;
            float height = bv.getBPD() / 1000f;

            //Background and borders
            float borderPaddingWidth
                = (borderPaddingStart + borderPaddingEnd) / 1000f;
            float borderPaddingHeight
                = (borderPaddingBefore + bv.getBorderAndPaddingWidthAfter()) / 1000f;
            drawBackAndBorders(bv, 0, 0, width + borderPaddingWidth, height + borderPaddingHeight);

            //Shift to content rectangle after border painting
            AffineTransform contentRectTransform = new AffineTransform();
            if ((level == -1) || ((level & 1) == 0)) {
                contentRectTransform.translate(borderPaddingStart, borderPaddingBefore);
            } else {
                contentRectTransform.translate(borderPaddingEnd, borderPaddingBefore);
            }

            if (!contentRectTransform.isIdentity()) {
                establishTransformationMatrix(contentRectTransform);
            }

            //Clipping
            if (bv.hasClip()) {
                clipRect(0f, 0f, width, height);
            }

            //Set up coordinate system for content rectangle
            AffineTransform contentTransform = ctm.toAffineTransform();
            if (!contentTransform.isIdentity()) {
                establishTransformationMatrix(contentTransform);
            }

            currentIPPosition = 0;
            currentBPPosition = 0;
            renderBlocks(bv, children);

            if (!contentTransform.isIdentity()) {
                restoreGraphicsState();
            }

            if (!contentRectTransform.isIdentity()) {
                restoreGraphicsState();
            }

            if (!positionTransform.isIdentity()) {
                restoreGraphicsState();
            }

            //For FIXED, we need to restore break out now we are done
            if (positioning == Block.FIXED) {
                if (breakOutList != null) {
                    restoreStateStackAfterBreakOut(breakOutList);
                }
            }

            currentIPPosition = saveIP;
            currentBPPosition = saveBP;
        } else {

            currentBPPosition += bv.getSpaceBefore();

            //borders and background in the old coordinate system
            handleBlockTraits(bv);

            //Advance to start of content area
            currentIPPosition += bv.getStartIndent();

            CTM tempctm = new CTM(containingIPPosition, currentBPPosition);
            ctm = tempctm.multiply(ctm);

            //Now adjust for border/padding
            currentBPPosition += borderPaddingBefore;

            Rectangle clippingRect = null;
            if (bv.hasClip()) {
                clippingRect = new Rectangle(currentIPPosition, currentBPPosition,
                        bv.getIPD(), bv.getBPD());
            }

            startVParea(ctm, clippingRect);
            currentIPPosition = 0;
            currentBPPosition = 0;
            renderBlocks(bv, children);
            endVParea();

            currentIPPosition = saveIP;
            currentBPPosition = saveBP;

            currentBPPosition += (bv.getAllocBPD());
        }
    }

    /** {@inheritDoc} */
    protected void renderReferenceArea(Block block) {
        // save position and offset
        int saveIP = currentIPPosition;
        int saveBP = currentBPPosition;

        //Establish a new coordinate system
        AffineTransform at = new AffineTransform();
        at.translate(currentIPPosition, currentBPPosition);
        at.translate(block.getXOffset(), block.getYOffset());
        at.translate(0, block.getSpaceBefore());

        if (!at.isIdentity()) {
            establishTransformationMatrix(at);
        }

        currentIPPosition = 0;
        currentBPPosition = 0;
        handleBlockTraits(block);

        List children = block.getChildAreas();
        if (children != null) {
            renderBlocks(block, children);
        }

        if (!at.isIdentity()) {
            restoreGraphicsState();
        }

        // stacked and relative blocks effect stacking
        currentIPPosition = saveIP;
        currentBPPosition = saveBP;
    }

    /** {@inheritDoc} */
    protected void renderFlow(NormalFlow flow) {
        // save position and offset
        int saveIP = currentIPPosition;
        int saveBP = currentBPPosition;

        //Establish a new coordinate system
        AffineTransform at = new AffineTransform();
        at.translate(currentIPPosition, currentBPPosition);

        if (!at.isIdentity()) {
            establishTransformationMatrix(at);
        }

        currentIPPosition = 0;
        currentBPPosition = 0;
        super.renderFlow(flow);

        if (!at.isIdentity()) {
            restoreGraphicsState();
        }

        // stacked and relative blocks effect stacking
        currentIPPosition = saveIP;
        currentBPPosition = saveBP;
    }

    /**
     * Concatenates the current transformation matrix with the given one, therefore establishing
     * a new coordinate system.
     * @param at the transformation matrix to process (coordinates in points)
     */
    protected abstract void concatenateTransformationMatrix(AffineTransform at);

    /**
     * Render an inline viewport.
     * This renders an inline viewport by clipping if necessary.
     * @param viewport the viewport to handle
     */
    public void renderInlineViewport(InlineViewport viewport) {
        int level = viewport.getBidiLevel();
        float x = currentIPPosition / 1000f;
        float y = (currentBPPosition + viewport.getBlockProgressionOffset()) / 1000f;
        float width = viewport.getIPD() / 1000f;
        float height = viewport.getBPD() / 1000f;
        // TODO: Calculate the border rect correctly.
        float borderPaddingStart = viewport.getBorderAndPaddingWidthStart() / 1000f;
        float borderPaddingEnd = viewport.getBorderAndPaddingWidthEnd() / 1000f;
        float borderPaddingBefore = viewport.getBorderAndPaddingWidthBefore() / 1000f;
        float borderPaddingAfter = viewport.getBorderAndPaddingWidthAfter() / 1000f;
        float bpwidth = borderPaddingStart + borderPaddingEnd;
        float bpheight = borderPaddingBefore + borderPaddingAfter;

        drawBackAndBorders(viewport, x, y, width + bpwidth, height + bpheight);

        if (viewport.hasClip()) {
            saveGraphicsState();
            if ((level == -1) || ((level & 1) == 0)) {
                clipRect(x + borderPaddingStart, y + borderPaddingBefore, width, height);
            } else {
                clipRect(x + borderPaddingEnd, y + borderPaddingBefore, width, height);
            }
        }
        super.renderInlineViewport(viewport);

        if (viewport.hasClip()) {
            restoreGraphicsState();
        }
    }

    /**
     * Restores the state stack after a break out.
     * @param breakOutList the state stack to restore.
     */
    protected abstract void restoreStateStackAfterBreakOut(List breakOutList);

    /**
     * Breaks out of the state stack to handle fixed block-containers.
     * @return the saved state stack to recreate later
     */
    protected abstract List breakOutOfStateStack();

    /** Saves the graphics state of the rendering engine. */
    protected abstract void saveGraphicsState();

    /** Restores the last graphics state of the rendering engine. */
    protected abstract void restoreGraphicsState();

    /** Indicates the beginning of a text object. */
    protected abstract void beginTextObject();

    /** Indicates the end of a text object. */
    protected abstract void endTextObject();

    /**
     * Paints the text decoration marks.
     * @param fm Current typeface
     * @param fontsize Current font size
     * @param inline inline area to paint the marks for
     * @param baseline position of the baseline
     * @param startx start IPD
     */
    protected void renderTextDecoration(FontMetrics fm, int fontsize, InlineArea inline,
                    int baseline, int startx) {
        boolean hasTextDeco = inline.hasUnderline()
                || inline.hasOverline()
                || inline.hasLineThrough();
        if (hasTextDeco) {
            endTextObject();
            float descender = fm.getDescender(fontsize) / 1000f;
            float capHeight = fm.getCapHeight(fontsize) / 1000f;
            float halfLineWidth = (descender / -8f) / 2f;
            float endx = (startx + inline.getIPD()) / 1000f;
            if (inline.hasUnderline()) {
                Color ct = (Color) inline.getTrait(Trait.UNDERLINE_COLOR);
                float y = baseline - descender / 2f;
                drawBorderLine(startx / 1000f, (y - halfLineWidth) / 1000f,
                        endx, (y + halfLineWidth) / 1000f,
                        true, true, Constants.EN_SOLID, ct);
            }
            if (inline.hasOverline()) {
                Color ct = (Color) inline.getTrait(Trait.OVERLINE_COLOR);
                float y = (float)(baseline - (1.1 * capHeight));
                drawBorderLine(startx / 1000f, (y - halfLineWidth) / 1000f,
                        endx, (y + halfLineWidth) / 1000f,
                        true, true, Constants.EN_SOLID, ct);
            }
            if (inline.hasLineThrough()) {
                Color ct = (Color) inline.getTrait(Trait.LINETHROUGH_COLOR);
                float y = (float)(baseline - (0.45 * capHeight));
                drawBorderLine(startx / 1000f, (y - halfLineWidth) / 1000f,
                        endx, (y + halfLineWidth) / 1000f,
                        true, true, Constants.EN_SOLID, ct);
            }
        }
    }

    /** Clip using the current path. */
    protected abstract void clip();

    /**
     * Clip using a rectangular area.
     * @param x the x coordinate (in points)
     * @param y the y coordinate (in points)
     * @param width the width of the rectangle (in points)
     * @param height the height of the rectangle (in points)
     */
    protected abstract void clipRect(float x, float y, float width, float height);

    /**
     * Moves the current point to (x, y), omitting any connecting line segment.
     * @param x x coordinate
     * @param y y coordinate
     */
    protected abstract void moveTo(float x, float y);

    /**
     * Appends a straight line segment from the current point to (x, y). The
     * new current point is (x, y).
     * @param x x coordinate
     * @param y y coordinate
     */
    protected abstract void lineTo(float x, float y);

    /**
     * Closes the current subpath by appending a straight line segment from
     * the current point to the starting point of the subpath.
     */
    protected abstract void closePath();

    /**
     * Fill a rectangular area.
     * @param x the x coordinate
     * @param y the y coordinate
     * @param width the width of the rectangle
     * @param height the height of the rectangle
     */
    protected abstract void fillRect(float x, float y, float width, float height);

    /**
     * Establishes a new foreground or fill color.
     * @param col the color to apply (null skips this operation)
     * @param fill true to set the fill color, false for the foreground color
     */
    protected abstract void updateColor(Color col, boolean fill);

    /**
     * Draw an image at the indicated location.
     * @param url the URI/URL of the image
     * @param pos the position of the image
     * @param foreignAttributes an optional Map with foreign attributes, may be null
     */
    protected abstract void drawImage(String url, Rectangle2D pos, Map foreignAttributes);

    /**
     * Draw an image at the indicated location.
     * @param url the URI/URL of the image
     * @param pos the position of the image
     */
    protected final void drawImage(String url, Rectangle2D pos) {
        drawImage(url, pos, null);
    }

    /**
     * Draw a border segment of an XSL-FO style border.
     * @param x1 starting x coordinate
     * @param y1 starting y coordinate
     * @param x2 ending x coordinate
     * @param y2 ending y coordinate
     * @param horz true for horizontal border segments, false for vertical border segments
     * @param startOrBefore true for border segments on the start or before edge,
     *                      false for end or after.
     * @param style the border style (one of Constants.EN_DASHED etc.)
     * @param col the color for the border segment
     */
    protected abstract void drawBorderLine(float x1, float y1, float x2, float y2, boolean horz,
            boolean startOrBefore, int style, Color col);

    /** {@inheritDoc} */
    public void renderForeignObject(ForeignObject fo, Rectangle2D pos) {
        endTextObject();
        Document doc = fo.getDocument();
        String ns = fo.getNameSpace();
        renderDocument(doc, ns, pos, fo.getForeignAttributes());
    }

    /**
     * Establishes a new coordinate system with the given transformation matrix.
     * The current graphics state is saved and the new coordinate system is concatenated.
     * @param at the transformation matrix
     */
    protected void establishTransformationMatrix(AffineTransform at) {
        saveGraphicsState();
        concatenateTransformationMatrix(UnitConv.mptToPt(at));
    }

}