summaryrefslogtreecommitdiff
path: root/reportbuilder/java/com/sun/star/report/pentaho/output/text/TextRawReportTarget.java
blob: 6ce89c5c032493d3742a82277148357119471a1d (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
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: TextRawReportTarget.java,v $
 * $Revision: 1.9 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
package com.sun.star.report.pentaho.output.text;

import com.sun.star.report.DataSourceFactory;
import java.io.IOException;
import java.io.OutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.Iterator;
import java.util.Map;

import com.sun.star.report.ImageService;
import com.sun.star.report.InputRepository;
import com.sun.star.report.OutputRepository;
import com.sun.star.report.pentaho.OfficeNamespaces;
import com.sun.star.report.OfficeToken;
import com.sun.star.report.pentaho.PentahoReportEngineMetaData;
import com.sun.star.report.pentaho.layoutprocessor.FormatValueUtility;
import com.sun.star.report.pentaho.model.OfficeMasterPage;
import com.sun.star.report.pentaho.model.OfficeMasterStyles;
import com.sun.star.report.pentaho.model.OfficeStyle;
import com.sun.star.report.pentaho.model.OfficeStyles;
import com.sun.star.report.pentaho.model.OfficeStylesCollection;
import com.sun.star.report.pentaho.model.PageSection;
import com.sun.star.report.pentaho.output.OfficeDocumentReportTarget;
import com.sun.star.report.pentaho.output.StyleUtilities;
import com.sun.star.report.pentaho.styles.LengthCalculator;
import java.util.ArrayList;
import org.jfree.layouting.input.style.values.CSSNumericValue;
import org.jfree.layouting.util.AttributeMap;
import org.jfree.report.DataSourceException;
import org.jfree.report.JFreeReportInfo;
import org.jfree.report.ReportProcessingException;
import org.jfree.report.flow.ReportJob;
import org.jfree.report.flow.ReportStructureRoot;
import org.jfree.report.flow.ReportTargetUtil;
import org.jfree.report.structure.Element;
import org.jfree.report.structure.Section;
import org.jfree.report.util.AttributeNameGenerator;
import org.jfree.report.util.IntegerCache;
import org.pentaho.reporting.libraries.base.util.FastStack;
import org.pentaho.reporting.libraries.base.util.IOUtils;
import org.pentaho.reporting.libraries.base.util.ObjectUtilities;
import org.pentaho.reporting.libraries.resourceloader.ResourceKey;
import org.pentaho.reporting.libraries.resourceloader.ResourceManager;
import org.pentaho.reporting.libraries.xmlns.common.AttributeList;
import org.pentaho.reporting.libraries.xmlns.writer.XmlWriter;
import org.pentaho.reporting.libraries.xmlns.writer.XmlWriterSupport;

/**
 * Creation-Date: 03.07.2006, 16:28:00
 *
 * @author Thomas Morgner
 */
public class TextRawReportTarget extends OfficeDocumentReportTarget
{

    private static final String ALWAYS = "always";
    private static final String KEEP_TOGETHER = "keep-together";
    private static final String KEEP_WITH_NEXT = "keep-with-next";
    private static final String MAY_BREAK_BETWEEN_ROWS = "may-break-between-rows";
    private static final String NAME = "name";
    private static final String NONE = "none";
    private static final String NORMAL = "normal";
    private static final String PARAGRAPH_PROPERTIES = "paragraph-properties";
    private static final String STANDARD = "Standard";
    private static final String TABLE_PROPERTIES = "table-properties";
    private static final String VARIABLES_HIDDEN_STYLE_WITH_KEEPWNEXT = "variables_paragraph_with_next";
    private static final String VARIABLES_HIDDEN_STYLE_WITHOUT_KEEPWNEXT = "variables_paragraph_without_next";
    private static final int TABLE_LAYOUT_VARIABLES_PARAGRAPH = 0;
    private static final int TABLE_LAYOUT_SINGLE_DETAIL_TABLE = 2;
    private static final int CP_SETUP = 0;
    private static final int CP_FIRST_TABLE = 1;
    private static final int CP_NEXT_TABLE = 2;

    // This is the initial state of the detail-band processing. It states, that we are now waiting for a
    // detail-band to be printed.
    private static final int DETAIL_SECTION_WAIT = 0;
    // The first detail section has started.
    private static final int DETAIL_SECTION_FIRST_STARTED = 1;
    // The first detail section has been printed.
    private static final int DETAIL_SECTION_FIRST_PRINTED = 2;
    // An other detail section has started
    private static final int DETAIL_SECTION_OTHER_STARTED = 3;
    // The other detail section has been printed.
    private static final int DETAIL_SECTION_OTHER_PRINTED = 4;
    private boolean pageFooterOnReportFooter;
    private boolean pageFooterOnReportHeader;
    private boolean pageHeaderOnReportFooter;
    private boolean pageHeaderOnReportHeader;
    private int contentProcessingState;
    private OfficeMasterPage currentMasterPage;
    private final FastStack activePageContext;
    private MasterPageFactory masterPageFactory;
    private LengthCalculator sectionHeight;
    private String variables;
    private PageBreakDefinition pageBreakDefinition;
    private VariablesDeclarations variablesDeclarations;
    private boolean columnBreakPending;
    private boolean sectionKeepTogether;
    private final AttributeNameGenerator sectionNames;
    private int detailBandProcessingState;
    private final int tableLayoutConfig;
    private int expectedTableRowCount;
    private boolean firstCellSeen;

    public TextRawReportTarget(final ReportJob reportJob,
            final ResourceManager resourceManager,
            final ResourceKey baseResource,
            final InputRepository inputRepository,
            final OutputRepository outputRepository,
            final String target,
            final ImageService imageService,
            final DataSourceFactory datasourcefactory)
            throws ReportProcessingException
    {
        super(reportJob, resourceManager, baseResource, inputRepository, outputRepository, target, imageService, datasourcefactory);
        activePageContext = new FastStack();
        this.sectionNames = new AttributeNameGenerator();

        this.tableLayoutConfig = TABLE_LAYOUT_SINGLE_DETAIL_TABLE;
    }

    protected String getTargetMimeType()
    {
        return "application/vnd.oasis.opendocument.text";
    }

    /**
     * Checks, whether a manual page break should be inserted at the next possible location.
     *
     * @return true, if a pagebreak is pending, false otherwise.
     */
    private boolean isPagebreakPending()
    {
        return pageBreakDefinition != null;
    }

    private boolean isResetPageNumber()
    {
        if (pageBreakDefinition == null)
        {
            return false;
        }
        return pageBreakDefinition.isResetPageNumber();
    }

    /**
     * Defines, whether a manual pagebreak should be inserted at the next possible location.
     *
     * @param pageBreakDefinition the new flag value.
     */
    private void setPagebreakDefinition(final PageBreakDefinition pageBreakDefinition)
    {
        this.pageBreakDefinition = pageBreakDefinition;
    }

    private PageBreakDefinition getPagebreakDefinition()
    {
        return pageBreakDefinition;
    }

    // todo
    private boolean isKeepTableWithNext()
    {
        final int keepTogetherState = getCurrentContext().getKeepTogether();
        if (keepTogetherState == PageContext.KEEP_TOGETHER_GROUP)
        {
            return true;
        }

        final boolean keepWithNext;
        if (keepTogetherState == PageContext.KEEP_TOGETHER_FIRST_DETAIL)
        {
            keepWithNext = (detailBandProcessingState == DETAIL_SECTION_WAIT);
        }
        else
        {
            keepWithNext = false;
        }
        return keepWithNext;
    }

    private boolean isSectionPagebreakAfter(final AttributeMap attrs)
    {
        final Object forceNewPage =
                attrs.getAttribute(OfficeNamespaces.OOREPORT_NS, "force-new-page");
        if ("after-section".equals(forceNewPage))
        {
            return true;
        }
        if ("before-after-section".equals(forceNewPage))
        {
            return true;
        }
        return false;
    }

    private boolean isSectionPagebreakBefore(final AttributeMap attrs)
    {
        final Object forceNewPage =
                attrs.getAttribute(OfficeNamespaces.OOREPORT_NS, "force-new-page");
        return "before-section".equals(forceNewPage) || "before-after-section".equals(forceNewPage);
    }

    private PageContext getCurrentContext()
    {
        return (PageContext) activePageContext.peek();
    }

    private String createMasterPage(final boolean printHeader,
            final boolean printFooter)
            throws ReportProcessingException
    {
        // create the master page for the report-header.
        // If there is a page-header or footer in the report that gets
        // surpressed on the report-header, we have to insert a pagebreak
        // afterwards.

        final String activePageFooter;
        // Check, whether the report header can have a page-header
        final PageContext context = getCurrentContext();
        if (printFooter)
        {
            activePageFooter = context.getPageFooterContent();
        }
        else
        {
            activePageFooter = null;
        }
        final String activePageHeader;
        if (printHeader)
        {
            // we have to insert a manual pagebreak after the report header.
            activePageHeader = context.getPageHeaderContent();
        }
        else
        {
            activePageHeader = null;
        }

        final String masterPageName;
        if (currentMasterPage == null ||
                !masterPageFactory.containsMasterPage(STANDARD, activePageHeader, activePageFooter))
        {

            final CSSNumericValue headerSize = context.getAllHeaderSize();
            final CSSNumericValue footerSize = context.getAllFooterSize();


            currentMasterPage = masterPageFactory.createMasterPage(STANDARD, activePageHeader, activePageFooter);

//      LOGGER.debug("Created a new master-page: " + currentMasterPage.getStyleName());

            // todo: Store the page-layouts as well.
            // The page layouts are derived from a common template, but as the
            // header-heights differ, we have to derive these beasts instead
            // of copying them

            final OfficeStylesCollection officeStylesCollection = getGlobalStylesCollection();
            final OfficeMasterStyles officeMasterStyles = officeStylesCollection.getMasterStyles();
            final String pageLayoutTemplate = currentMasterPage.getPageLayout();
            if (pageLayoutTemplate == null)
            {
                // there is no pagelayout. Create one ..
                final String derivedLayout = masterPageFactory.createPageStyle(getGlobalStylesCollection().getAutomaticStyles(), headerSize, footerSize);
                currentMasterPage.setPageLayout(derivedLayout);
            }
            else
            {
                final String derivedLayout = masterPageFactory.derivePageStyle(pageLayoutTemplate,
                        getPredefinedStylesCollection().getAutomaticStyles(),
                        getGlobalStylesCollection().getAutomaticStyles(), headerSize, footerSize);
                currentMasterPage.setPageLayout(derivedLayout);
            }
            officeMasterStyles.addMasterPage(currentMasterPage);
            masterPageName = currentMasterPage.getStyleName();
        }
        else
        {
            // retrieve the master-page.
            final OfficeMasterPage masterPage = masterPageFactory.getMasterPage(STANDARD, activePageHeader, activePageFooter);
            if (ObjectUtilities.equal(masterPage.getStyleName(), currentMasterPage.getStyleName()))
            {
                // They are the same,
                masterPageName = null;
            }
            else
            {
                // reuse the existing one ..
                currentMasterPage = masterPage;
                masterPageName = currentMasterPage.getStyleName();
            }
        }

        // if either the pageheader or footer are *not* printed with the
        // report header, then this implies that we have to insert a manual
        // pagebreak at the end of the section.

        if ((!printHeader && context.getHeader() != null) ||
                (!printFooter && context.getFooter() != null))
        {
            setPagebreakDefinition(new PageBreakDefinition(isResetPageNumber()));
        }

        return masterPageName;
    }

    private boolean isColumnBreakPending()
    {
        return columnBreakPending;
    }

    private void setColumnBreakPending(final boolean columnBreakPending)
    {
        this.columnBreakPending = columnBreakPending;
    }

    private Integer parseInt(final Object value)
    {
        if (value instanceof Number)
        {
            final Number n = (Number) value;
            return IntegerCache.getInteger(n.intValue());
        }
        if (value instanceof String)
        {
            try
            {
                return IntegerCache.getInteger(Integer.parseInt((String) value));
            }
            catch (NumberFormatException nfe)
            {
                //return null; // ignore
            }
        }
        return null;
    }

    private BufferState applyColumnsToPageBand(final BufferState contents,
            final int numberOfColumns)
            throws IOException, ReportProcessingException
    {
        if (numberOfColumns <= 1)
        {
            return contents;
        }
        startBuffering(getGlobalStylesCollection(), true);
        // derive section style ..

        // This is a rather cheap solution to the problem. In a sane world, we would have to feed the
        // footer multiple times. Right now, we simply rely on the balacing, which should make sure that
        // the column's content are evenly distributed.
        final XmlWriter writer = getXmlWriter();
        final AttributeList attrs = new AttributeList();
        attrs.setAttribute(OfficeNamespaces.TEXT_NS, OfficeToken.STYLE_NAME, generateSectionStyle(numberOfColumns));
        attrs.setAttribute(OfficeNamespaces.TEXT_NS, NAME, sectionNames.generateName("Section"));
        writer.writeTag(OfficeNamespaces.TEXT_NS, "section", attrs, XmlWriterSupport.OPEN);
        for (int i = 0; i < numberOfColumns; i++)
        {
            writer.writeStream(contents.getXmlAsReader());
        }

        writer.writeCloseTag();
        return finishBuffering();
    }

    private String generateSectionStyle(final int columnCount)
    {
        final OfficeStyles automaticStyles = getStylesCollection().getAutomaticStyles();
        final String styleName = getAutoStyleNameGenerator().generateName("auto_section_style");

        final Section sectionProperties = new Section();
        sectionProperties.setNamespace(OfficeNamespaces.STYLE_NS);
        sectionProperties.setType("section-properties");
        sectionProperties.setAttribute(OfficeNamespaces.FO_NS, OfficeToken.BACKGROUND_COLOR, "transparent");
        sectionProperties.setAttribute(OfficeNamespaces.TEXT_NS, "dont-balance-text-columns", OfficeToken.FALSE);
        sectionProperties.setAttribute(OfficeNamespaces.STYLE_NS, "editable", OfficeToken.FALSE);

        if (columnCount > 1)
        {
            final Section columns = new Section();
            columns.setNamespace(OfficeNamespaces.STYLE_NS);
            columns.setType("columns");
            columns.setAttribute(OfficeNamespaces.FO_NS, "column-count", String.valueOf(columnCount));
            columns.setAttribute(OfficeNamespaces.STYLE_NS, "column-gap", "0cm");
            sectionProperties.addNode(columns);

//    final Section columnSep = new Section();
//    columnSep.setNamespace(OfficeNamespaces.STYLE_NS);
//    columnSep.setType("column-sep");
//    columnSep.setAttribute(OfficeNamespaces.STYLE_NS, "width", "0.035cm");
//    columnSep.setAttribute(OfficeNamespaces.STYLE_NS, "color", "#000000");
//    columnSep.setAttribute(OfficeNamespaces.STYLE_NS, "height", "100%");
//    columns.addNode(columnSep);

            for (int i = 0; i < columnCount; i++)
            {
                final Section column = new Section();
                column.setNamespace(OfficeNamespaces.STYLE_NS);
                column.setType("column");
                column.setAttribute(OfficeNamespaces.STYLE_NS, "rel-width", "1*");
                column.setAttribute(OfficeNamespaces.FO_NS, "start-indent", "0cm");
                column.setAttribute(OfficeNamespaces.FO_NS, "end-indent", "0cm");
                columns.addNode(column);
            }
        }

        final OfficeStyle style = new OfficeStyle();
        style.setNamespace(OfficeNamespaces.STYLE_NS);
        style.setType("style");
        style.setAttribute(OfficeNamespaces.STYLE_NS, NAME, styleName);
        style.setAttribute(OfficeNamespaces.STYLE_NS, "family", "section");
        style.addNode(sectionProperties);

        automaticStyles.addStyle(style);
        return styleName;
    }

    /**
     * Starts the output of a new office document. This method writes the generic 'office:document-content' tag along with
     * all known namespace declarations.
     *
     * @param report the report object.
     * @throws org.jfree.report.DataSourceException
     *          if there was an error accessing the datasource
     * @throws org.jfree.report.ReportProcessingException
     *          if some other error occured.
     */
    public void startReport(final ReportStructureRoot report)
            throws DataSourceException, ReportProcessingException
    {
        super.startReport(report);
        variablesDeclarations = new VariablesDeclarations();
        detailBandProcessingState = DETAIL_SECTION_WAIT;
        sectionNames.reset();

        pageFooterOnReportFooter = false;
        pageFooterOnReportHeader = false;
        pageHeaderOnReportFooter = false;
        pageHeaderOnReportHeader = false;
        contentProcessingState = TextRawReportTarget.CP_SETUP;

        activePageContext.clear();
        activePageContext.push(new PageContext());

        final OfficeStylesCollection predefStyles = getPredefinedStylesCollection();
        masterPageFactory = new MasterPageFactory(predefStyles.getMasterStyles());

        predefStyles.getAutomaticStyles().addStyle(createVariablesStyle(true));
        predefStyles.getAutomaticStyles().addStyle(createVariablesStyle(false));
    }

    private OfficeStyle createVariablesStyle(final boolean keepWithNext)
    {
        final OfficeStyle variablesSectionStyle = new OfficeStyle();
        variablesSectionStyle.setStyleFamily(OfficeToken.PARAGRAPH);
        if (keepWithNext)
        {
            variablesSectionStyle.setStyleName(TextRawReportTarget.VARIABLES_HIDDEN_STYLE_WITH_KEEPWNEXT);
        }
        else
        {
            variablesSectionStyle.setStyleName(TextRawReportTarget.VARIABLES_HIDDEN_STYLE_WITHOUT_KEEPWNEXT);
        }

        final Section paragraphProps = new Section();
        paragraphProps.setNamespace(OfficeNamespaces.STYLE_NS);
        paragraphProps.setType(PARAGRAPH_PROPERTIES);
        paragraphProps.setAttribute(OfficeNamespaces.FO_NS, OfficeToken.BACKGROUND_COLOR, "transparent");
        paragraphProps.setAttribute(OfficeNamespaces.FO_NS, "text-align", "start");
        paragraphProps.setAttribute(OfficeNamespaces.FO_NS, KEEP_WITH_NEXT, ALWAYS);
        paragraphProps.setAttribute(OfficeNamespaces.FO_NS, KEEP_TOGETHER, ALWAYS);
        paragraphProps.setAttribute(OfficeNamespaces.STYLE_NS, "vertical-align", "top");
        variablesSectionStyle.addNode(paragraphProps);

        final Section textProps = new Section();
        textProps.setNamespace(OfficeNamespaces.STYLE_NS);
        textProps.setType("text-properties");
        textProps.setAttribute(OfficeNamespaces.FO_NS, "font-variant", NORMAL);
        textProps.setAttribute(OfficeNamespaces.FO_NS, "text-transform", NONE);
        textProps.setAttribute(OfficeNamespaces.FO_NS, "color", "#ffffff");
        textProps.setAttribute(OfficeNamespaces.STYLE_NS, "text-outline", OfficeToken.FALSE);
        textProps.setAttribute(OfficeNamespaces.STYLE_NS, "text-blinking", OfficeToken.FALSE);
        textProps.setAttribute(OfficeNamespaces.STYLE_NS, "text-line-through-style", NONE);
        textProps.setAttribute(OfficeNamespaces.STYLE_NS, "text-line-through-mode", "continuous");
        textProps.setAttribute(OfficeNamespaces.STYLE_NS, "text-position", "0% 100%");
        textProps.setAttribute(OfficeNamespaces.STYLE_NS, "font-name", "Tahoma");
        textProps.setAttribute(OfficeNamespaces.FO_NS, "font-size", "1pt");
        textProps.setAttribute(OfficeNamespaces.FO_NS, "letter-spacing", NORMAL);
        textProps.setAttribute(OfficeNamespaces.STYLE_NS, "letter-kerning", OfficeToken.FALSE);
        textProps.setAttribute(OfficeNamespaces.FO_NS, "font-style", NORMAL);
        textProps.setAttribute(OfficeNamespaces.FO_NS, "text-shadow", NONE);
        textProps.setAttribute(OfficeNamespaces.STYLE_NS, "text-underline-style", NONE);
        textProps.setAttribute(OfficeNamespaces.STYLE_NS, "text-underline-mode", "continuous");
        textProps.setAttribute(OfficeNamespaces.FO_NS, "font-weight", NORMAL);
        textProps.setAttribute(OfficeNamespaces.STYLE_NS, "text-rotation-angle", "0");
        textProps.setAttribute(OfficeNamespaces.STYLE_NS, "text-emphasize", NONE);
        textProps.setAttribute(OfficeNamespaces.STYLE_NS, "text-combine", NONE);
        textProps.setAttribute(OfficeNamespaces.STYLE_NS, "text-combine-start-char", "");
        textProps.setAttribute(OfficeNamespaces.STYLE_NS, "text-combine-end-char", "");
        textProps.setAttribute(OfficeNamespaces.STYLE_NS, "text-blinking", OfficeToken.FALSE);
        textProps.setAttribute(OfficeNamespaces.STYLE_NS, "text-scale", "100%");
        textProps.setAttribute(OfficeNamespaces.STYLE_NS, "font-relief", NONE);
        textProps.setAttribute(OfficeNamespaces.STYLE_NS, "text-display", NONE);
        variablesSectionStyle.addNode(textProps);
        return variablesSectionStyle;
    }

    protected void startContent(final AttributeMap attrs)
            throws IOException, DataSourceException, ReportProcessingException
    {
        final XmlWriter xmlWriter = getXmlWriter();
        xmlWriter.writeTag(OfficeNamespaces.OFFICE_NS, "text", null, XmlWriterSupport.OPEN);

        writeNullDate();

        // now start the buffering. We have to insert the variables declaration
        // later ..
        startBuffering(getStylesCollection(), true);

        final Object columnCountRaw = attrs.getAttribute(OfficeNamespaces.FO_NS, "column-count");
        final Integer colCount = parseInt(columnCountRaw);
        if (colCount != null)
        {
            final PageContext pageContext = getCurrentContext();
            pageContext.setColumnCount(colCount);
        }

    }

    protected void startOther(final AttributeMap attrs)
            throws IOException, DataSourceException, ReportProcessingException
    {
        final String namespace = ReportTargetUtil.getNamespaceFromAttribute(attrs);
        final String elementType = ReportTargetUtil.getElemenTypeFromAttribute(attrs);

        if (ObjectUtilities.equal(JFreeReportInfo.REPORT_NAMESPACE, namespace))
        {
            if (ObjectUtilities.equal(OfficeToken.IMAGE, elementType))
            {
                startImageProcessing(attrs);
            }
            else if (ObjectUtilities.equal(OfficeToken.OBJECT_OLE, elementType) && getCurrentRole() != ROLE_TEMPLATE)
            {
                startChartProcessing(attrs);
            }
            return;
        }
        else if (isFilteredNamespace(namespace))
        {
            throw new IllegalStateException("This element should be hidden: " +
                    namespace + ", " + elementType);
        }

        if (isTableMergeActive() && detailBandProcessingState == DETAIL_SECTION_OTHER_PRINTED && ObjectUtilities.equal(OfficeNamespaces.TABLE_NS, namespace) && ObjectUtilities.equal(OfficeToken.TABLE_COLUMNS, elementType))
        {
            // Skip the columns section if the tables get merged..
            startBuffering(getStylesCollection(), true);
            return;
        }
        else
        {
            openSection();

            final boolean isTableNS = ObjectUtilities.equal(OfficeNamespaces.TABLE_NS, namespace);
            if (isTableNS)
            {
                if (ObjectUtilities.equal(OfficeToken.TABLE, elementType))
                {
                    startTable(attrs);
                    return;
                }

                if (ObjectUtilities.equal(OfficeToken.TABLE_ROW, elementType))
                {
                    startRow(attrs);
                    return;
                }
            }


            if (ObjectUtilities.equal(OfficeNamespaces.TEXT_NS, namespace))
            {
                if (ObjectUtilities.equal("variable-set", elementType))
                {
                    // update the variables-declaration thingie ..
                    final String varName = (String) attrs.getAttribute(OfficeNamespaces.TEXT_NS, NAME);
                    final String varType = (String) attrs.getAttribute(OfficeNamespaces.OFFICE_NS, FormatValueUtility.VALUE_TYPE);
                    final String newVarName = variablesDeclarations.produceVariable(varName, varType);
                    attrs.setAttribute(OfficeNamespaces.TEXT_NS, NAME, newVarName);
                }
                else if (ObjectUtilities.equal("variable-get", elementType))
                {
                    final String varName = (String) attrs.getAttribute(OfficeNamespaces.TEXT_NS, NAME);
                    final String varType = (String) attrs.getAttribute(OfficeNamespaces.OFFICE_NS, FormatValueUtility.VALUE_TYPE);
                    final String newVarName = variablesDeclarations.produceVariable(varName, varType);
                    attrs.setAttribute(OfficeNamespaces.TEXT_NS, NAME, newVarName);
                // this one must not be written, as the DTD does not declare it.
                // attrs.setAttribute(OfficeNamespaces.OFFICE_NS, FormatValueUtility.VALUE_TYPE, null);
                }
            }

            if (tableLayoutConfig == TABLE_LAYOUT_VARIABLES_PARAGRAPH && variables != null)
            {
                // This cannot happen as long as the report sections only contain tables. But at some point in the
                // future they will be made of paragraphs, and then we are prepared ..
                // LOGGER.debug("Variables-Section in own paragraph " + variables);

                StyleUtilities.copyStyle(OfficeToken.PARAGRAPH,
                        TextRawReportTarget.VARIABLES_HIDDEN_STYLE_WITH_KEEPWNEXT, getStylesCollection(),
                        getGlobalStylesCollection(), getPredefinedStylesCollection());
                final XmlWriter xmlWriter = getXmlWriter();
                xmlWriter.writeTag(OfficeNamespaces.TEXT_NS, OfficeToken.P, OfficeToken.STYLE_NAME,
                        TextRawReportTarget.VARIABLES_HIDDEN_STYLE_WITH_KEEPWNEXT, XmlWriterSupport.OPEN);
                xmlWriter.writeText(variables);
                xmlWriter.writeCloseTag();
                variables = null;
            }

            final boolean keepTogetherOnParagraph = true;

            if (keepTogetherOnParagraph)
            {
                if (ReportTargetUtil.isElementOfType(OfficeNamespaces.TEXT_NS, OfficeToken.P, attrs))
                {
                    final int keepTogetherState = getCurrentContext().getKeepTogether();
                    if (!firstCellSeen && (sectionKeepTogether || keepTogetherState == PageContext.KEEP_TOGETHER_GROUP))
                    {
                        OfficeStyle style = null;
                        final String styleName = (String) attrs.getAttribute(OfficeNamespaces.TEXT_NS, OfficeToken.STYLE_NAME);
                        if (styleName == null)
                        {
                            final boolean keep = (keepTogetherState == PageContext.KEEP_TOGETHER_GROUP || expectedTableRowCount > 0) && isParentKeepTogether();
                            final ArrayList propertyNameSpaces = new ArrayList();
                            final ArrayList propertyNames = new ArrayList();
                            final ArrayList propertyValues = new ArrayList();

                            propertyNameSpaces.add(OfficeNamespaces.FO_NS);
                            propertyNameSpaces.add(OfficeNamespaces.FO_NS);
                            propertyNames.add(KEEP_TOGETHER);
                            propertyValues.add(ALWAYS);
                            if (keep)
                            {
                                propertyNames.add(KEEP_WITH_NEXT);
                                propertyValues.add(ALWAYS);
                            }
                            else
                            {
                                propertyNames.add(KEEP_WITH_NEXT);
                                propertyValues.add(null);
                            }
                            style = StyleUtilities.queryStyleByProperties(getStylesCollection(), OfficeToken.PARAGRAPH, PARAGRAPH_PROPERTIES, propertyNameSpaces, propertyNames, propertyValues);
                        }
                        if (style == null)
                        {
                            style = deriveStyle(OfficeToken.PARAGRAPH, styleName);
                            // Lets set the 'keep-together' flag..

                            Element paragraphProps = style.getParagraphProperties();
                            if (paragraphProps == null)
                            {
                                paragraphProps = new Section();
                                paragraphProps.setNamespace(OfficeNamespaces.STYLE_NS);
                                paragraphProps.setType(PARAGRAPH_PROPERTIES);
                                style.addNode(paragraphProps);
                            }
                            paragraphProps.setAttribute(OfficeNamespaces.FO_NS, KEEP_TOGETHER, ALWAYS);

                            // We prevent pagebreaks within the two adjacent rows (this one and the next one) if
                            // either a group-wide keep-together is defined or if we haven't reached the end of the
                            // current section yet.
                            if ((keepTogetherState == PageContext.KEEP_TOGETHER_GROUP || expectedTableRowCount > 0) && isParentKeepTogether())
                            {
                                paragraphProps.setAttribute(OfficeNamespaces.FO_NS, KEEP_WITH_NEXT, ALWAYS);
                            }
                        }

                        attrs.setAttribute(OfficeNamespaces.TEXT_NS, OfficeToken.STYLE_NAME, style.getStyleName());
                    }
                }
            }

            if (ObjectUtilities.equal(OfficeNamespaces.DRAWING_NS, namespace) && ObjectUtilities.equal(OfficeToken.FRAME, elementType))
            {
                final String styleName = (String) attrs.getAttribute(OfficeNamespaces.DRAWING_NS, OfficeToken.STYLE_NAME);
                final OfficeStyle predefAutoStyle = getPredefinedStylesCollection().getAutomaticStyles().getStyle(OfficeToken.GRAPHIC, styleName);
                if (predefAutoStyle != null)
                {
                    // special ole handling
                    final Element graphicProperties = predefAutoStyle.getGraphicProperties();
                    graphicProperties.setAttribute(OfficeNamespaces.STYLE_NS, VERTICAL_POS, "from-top");
                    graphicProperties.setAttribute(OfficeNamespaces.STYLE_NS, HORIZONTAL_POS, "from-left");
                    graphicProperties.setAttribute(OfficeNamespaces.STYLE_NS, "vertical-rel", "paragraph-content");
                    graphicProperties.setAttribute(OfficeNamespaces.STYLE_NS, "horizontal-rel", "paragraph");
                    graphicProperties.setAttribute(OfficeNamespaces.STYLE_NS, "flow-with-text", "false");
                    graphicProperties.setAttribute(OfficeNamespaces.DRAWING_NS, "ole-draw-aspect", "1");

                // attrs.setAttribute(OfficeNamespaces.DRAWING_NS, OfficeToken.STYLE_NAME, predefAutoStyle.getStyleName());
                }
            }

            // process the styles as usual
            performStyleProcessing(attrs);
            final XmlWriter xmlWriter = getXmlWriter();
            final AttributeList attrList = buildAttributeList(attrs);
            xmlWriter.writeTag(namespace, elementType, attrList, XmlWriterSupport.OPEN);

            if (ReportTargetUtil.isElementOfType(OfficeNamespaces.TEXT_NS, OfficeToken.P, attrs) &&
                tableLayoutConfig != TABLE_LAYOUT_VARIABLES_PARAGRAPH && variables != null)
            {
                //LOGGER.debug("Variables-Section in existing cell " + variables);
                xmlWriter.writeText(variables);
                variables = null;
            }
        }
    }

    private void startRow(final AttributeMap attrs)
            throws IOException, ReportProcessingException
    {
        firstCellSeen = false;
        expectedTableRowCount -= 1;
        final String rowStyle = (String) attrs.getAttribute(OfficeNamespaces.TABLE_NS, OfficeToken.STYLE_NAME);
        final CSSNumericValue rowHeight = computeRowHeight(rowStyle);
        // LOGGER.debug("Adding row-Style: " + rowStyle + " " + rowHeight);
        sectionHeight.add(rowHeight);

//    if (expectedTableRowCount > 0)
//    {
//      // Some other row. Create a keep-together
//
//    }
//    else
//    {
//      // This is the last row before the section will end.
//      // or (in some weird cases) There is no information when the row will end.
//      // Anyway, if we are here, we do not create a keep-together style on the table-row ..
//    }
        // process the styles as usual
        performStyleProcessing(attrs);

        final AttributeList attrList = buildAttributeList(attrs);
        getXmlWriter().writeTag(OfficeNamespaces.TABLE_NS, OfficeToken.TABLE_ROW, attrList, XmlWriterSupport.OPEN);
    }

    private void startTable(final AttributeMap attrs)
            throws ReportProcessingException, IOException
    {
        final Integer trc = (Integer) attrs.getAttribute(JFreeReportInfo.REPORT_NAMESPACE, "table-row-count");
        if (trc == null)
        {
            expectedTableRowCount = -1;
        }
        else
        {
            expectedTableRowCount = trc.intValue();
        }

        if (isSectionPagebreakBefore(attrs))
        {
            // force a pagebreak ..
            setPagebreakDefinition(new PageBreakDefinition(isResetPageNumber()));
        }

        // its a table. This means, it is a root-level element
        final PageBreakDefinition breakDefinition;
        String masterPageName = null;
        final int currentRole = getCurrentRole();
        if (contentProcessingState == TextRawReportTarget.CP_FIRST_TABLE)
        {
            contentProcessingState = TextRawReportTarget.CP_NEXT_TABLE;

            // Processing the report header now.
            if (currentRole == OfficeDocumentReportTarget.ROLE_REPORT_HEADER)
            {
                breakDefinition = new PageBreakDefinition(isResetPageNumber());
                masterPageName = createMasterPage(pageHeaderOnReportHeader, pageFooterOnReportHeader);
                if (masterPageName == null)
                {
                    // we should always have a master-page ...
                    masterPageName = currentMasterPage.getStyleName();
                }
            }
            else if (currentRole == OfficeDocumentReportTarget.ROLE_REPORT_FOOTER)
            {
                breakDefinition = new PageBreakDefinition(isResetPageNumber());
                masterPageName = createMasterPage(pageHeaderOnReportFooter, pageFooterOnReportFooter);
                if (masterPageName == null && isSectionPagebreakBefore(attrs))
                {
                    // If we have a manual pagebreak, then activate the current master-page again.
                    masterPageName = currentMasterPage.getStyleName();
                }
            // But we skip this (and therefore the resulting pagebreak) if there is no manual break
            // and no other condition that would force an break.
            }
            else if (currentRole == OfficeDocumentReportTarget.ROLE_REPEATING_GROUP_HEADER || currentRole == OfficeDocumentReportTarget.ROLE_REPEATING_GROUP_FOOTER)
            {
                breakDefinition = null;
            // no pagebreaks ..
            }
            else if (currentMasterPage == null ||
                    isPagebreakPending())
            {
                // Must be the first table, as we have no master-page yet.
                masterPageName = createMasterPage(true, true);
                setPagebreakDefinition(null);
                if (masterPageName == null)
                {
                    // we should always have a master-page ...
                    masterPageName = currentMasterPage.getStyleName();
                }
                breakDefinition = new PageBreakDefinition(isResetPageNumber());
            }
            else
            {
                breakDefinition = null;
            }
        }
        else if (isPagebreakPending() &&
                currentRole != OfficeDocumentReportTarget.ROLE_REPEATING_GROUP_HEADER &&
                currentRole != OfficeDocumentReportTarget.ROLE_REPEATING_GROUP_FOOTER)
        {
            // Derive an automatic style for the pagebreak.
//      LOGGER.debug("Manual pagebreak (within the section): " + getCurrentRole());
            breakDefinition = getPagebreakDefinition();
            setPagebreakDefinition(null);
            masterPageName = createMasterPage(true, true);
            if (masterPageName == null || isSectionPagebreakBefore(attrs))
            {
                // If we have a manual pagebreak, then activate the current master-page again.
                masterPageName = currentMasterPage.getStyleName();
            }
        }
        else
        {
            breakDefinition = null;
        }

        final XmlWriter xmlWriter = getXmlWriter();
        if (detailBandProcessingState == DETAIL_SECTION_OTHER_PRINTED &&
                masterPageName != null)
        {
            // close the last table-tag, we will open a new one
            xmlWriter.writeCloseTag();
            // Reset the detail-state to 'started' so that the table's columns get printed now.
            detailBandProcessingState = DETAIL_SECTION_OTHER_STARTED;
        }

        if (tableLayoutConfig == TABLE_LAYOUT_VARIABLES_PARAGRAPH && variables != null)
        {
            if (masterPageName != null)
            {
                // write a paragraph that uses the VARIABLES_HIDDEN_STYLE as
                // primary style. Derive that one and add the manual pagebreak.
                // The predefined style already has the 'keep-together' flags set.
//        LOGGER.debug("Variables-Section with new Master-Page " + variables + " " + masterPageName);

                final OfficeStyle style = deriveStyle(OfficeToken.PARAGRAPH, TextRawReportTarget.VARIABLES_HIDDEN_STYLE_WITH_KEEPWNEXT);
                style.setAttribute(OfficeNamespaces.STYLE_NS, "master-page-name", masterPageName);
                if (breakDefinition.isResetPageNumber())
                {
                    final Element paragraphProps = produceFirstChild(style, OfficeNamespaces.STYLE_NS, PARAGRAPH_PROPERTIES);
                    paragraphProps.setAttribute(OfficeNamespaces.STYLE_NS, "page-number", "1");
                }
                if (isColumnBreakPending())
                {
                    final Element paragraphProps = produceFirstChild(style, OfficeNamespaces.STYLE_NS, PARAGRAPH_PROPERTIES);
                    paragraphProps.setAttribute(OfficeNamespaces.FO_NS, "break-before", "column");
                    setColumnBreakPending(false);
                }
                xmlWriter.writeTag(OfficeNamespaces.TEXT_NS, OfficeToken.P, OfficeToken.STYLE_NAME, style.getStyleName(), XmlWriterSupport.OPEN);

                masterPageName = null;
            //breakDefinition = null;
            }
            else if (isColumnBreakPending())
            {
                setColumnBreakPending(false);

                final OfficeStyle style = deriveStyle(OfficeToken.PARAGRAPH, TextRawReportTarget.VARIABLES_HIDDEN_STYLE_WITH_KEEPWNEXT);
                final Element paragraphProps = produceFirstChild(style, OfficeNamespaces.STYLE_NS, PARAGRAPH_PROPERTIES);
                paragraphProps.setAttribute(OfficeNamespaces.STYLE_NS, "page-number", "1");

                xmlWriter.writeTag(OfficeNamespaces.TEXT_NS, OfficeToken.P, OfficeToken.STYLE_NAME, style.getStyleName(), XmlWriterSupport.OPEN);
            }
            else
            {
                // Write a paragraph without adding the pagebreak. We can reuse the global style, but we have to make
                // sure that the style is part of the current 'auto-style' collection.
//        LOGGER.debug("Variables-Section " + variables);

                StyleUtilities.copyStyle(OfficeToken.PARAGRAPH,
                        TextRawReportTarget.VARIABLES_HIDDEN_STYLE_WITH_KEEPWNEXT, getStylesCollection(),
                        getGlobalStylesCollection(), getPredefinedStylesCollection());
                xmlWriter.writeTag(OfficeNamespaces.TEXT_NS, OfficeToken.P, OfficeToken.STYLE_NAME,
                        TextRawReportTarget.VARIABLES_HIDDEN_STYLE_WITH_KEEPWNEXT, XmlWriterSupport.OPEN);
            }
            xmlWriter.writeText(variables);
            xmlWriter.writeCloseTag();
            variables = null;
        }

        final boolean keepWithNext = isKeepTableWithNext();
        final boolean localKeepTogether = OfficeToken.TRUE.equals(attrs.getAttribute(OfficeNamespaces.OOREPORT_NS, KEEP_TOGETHER));
        final boolean tableMergeActive = isTableMergeActive();
        if (tableMergeActive)
        {
            this.sectionKeepTogether = localKeepTogether;
        }
        else
        {
            this.sectionKeepTogether = false;

        }

        // Check, whether we have a reason to derive a style...
        if (masterPageName != null ||
                (!tableMergeActive && (localKeepTogether || keepWithNext)) || isColumnBreakPending())
        {
            final String styleName = (String) attrs.getAttribute(OfficeNamespaces.TABLE_NS, OfficeToken.STYLE_NAME);
            final OfficeStyle style = deriveStyle("table", styleName);

            if (masterPageName != null)
            {
//        LOGGER.debug("Starting a new MasterPage: " + masterPageName);
                // Patch the current styles.
                // This usually only happens on Table-Styles or Paragraph-Styles
                style.setAttribute(OfficeNamespaces.STYLE_NS, "master-page-name", masterPageName);
                if (breakDefinition.isResetPageNumber())
                {
                    final Element paragraphProps = produceFirstChild(style, OfficeNamespaces.STYLE_NS, PARAGRAPH_PROPERTIES);
                    paragraphProps.setAttribute(OfficeNamespaces.STYLE_NS, "page-number", "1");
                }
            }
            if (isColumnBreakPending())
            {
                final Element paragraphProps = produceFirstChild(style, OfficeNamespaces.STYLE_NS, PARAGRAPH_PROPERTIES);
                paragraphProps.setAttribute(OfficeNamespaces.FO_NS, "break-before", "column");
                setColumnBreakPending(false);
            }

            // Inhibit breaks inside the table only if it has been defined and if we do not create one single
            // big detail section. In that case, this flag would be invalid and would cause layout-errors.
            if (!tableMergeActive)
            {
                if (localKeepTogether)
                {
                    final Element tableProps = produceFirstChild(style, OfficeNamespaces.STYLE_NS, TABLE_PROPERTIES);
                    tableProps.setAttribute(OfficeNamespaces.STYLE_NS, MAY_BREAK_BETWEEN_ROWS, OfficeToken.FALSE);
                }
            }
            else
            {
                if (detailBandProcessingState == DETAIL_SECTION_WAIT)
                {
                    detailBandProcessingState = DETAIL_SECTION_FIRST_STARTED;
                }
                else if (detailBandProcessingState == DETAIL_SECTION_FIRST_PRINTED)
                {
                    detailBandProcessingState = DETAIL_SECTION_OTHER_STARTED;
                }
            }
            if (keepWithNext)
            {
                boolean addKeepWithNext = true;
                if (currentRole == ROLE_GROUP_FOOTER)
                {
                    addKeepWithNext = isParentKeepTogether();
                }

                final Element tableProps = produceFirstChild(style, OfficeNamespaces.STYLE_NS, TABLE_PROPERTIES);
                tableProps.setAttribute(OfficeNamespaces.STYLE_NS, MAY_BREAK_BETWEEN_ROWS, OfficeToken.FALSE);
                if (addKeepWithNext)
                {
                    tableProps.setAttribute(OfficeNamespaces.FO_NS, KEEP_WITH_NEXT, ALWAYS);
                    // A keep-with-next does not work, if the may-break-betweek rows is not set to false ..
                }
            }
            attrs.setAttribute(OfficeNamespaces.TABLE_NS, OfficeToken.STYLE_NAME, style.getStyleName());
        // no need to copy the styles, this was done while deriving the
        // style ..
        }
        else
        {
            // Check, whether we may be able to skip the table.
            if (tableMergeActive)
            {
                if (detailBandProcessingState == DETAIL_SECTION_OTHER_PRINTED)
                {
                    // Skip the whole thing ..
                    return;
                }
                else if (detailBandProcessingState == DETAIL_SECTION_WAIT)
                {
                    if (keepWithNext)
                    {
                        final String styleName = (String) attrs.getAttribute(OfficeNamespaces.TABLE_NS, OfficeToken.STYLE_NAME);

                        final OfficeStyle style = deriveStyle(OfficeToken.TABLE, styleName);
                        final Element tableProps = produceFirstChild(style, OfficeNamespaces.STYLE_NS, TABLE_PROPERTIES);
                        // A keep-with-next does not work, if the may-break-betweek rows is not set to false ..
                        tableProps.setAttribute(OfficeNamespaces.STYLE_NS, MAY_BREAK_BETWEEN_ROWS, OfficeToken.FALSE);
                        final String hasGroupFooter = (String) attrs.getAttribute(JFreeReportInfo.REPORT_NAMESPACE, "has-group-footer");
                        if (hasGroupFooter != null && hasGroupFooter.equals(OfficeToken.TRUE))
                        {
                            tableProps.setAttribute(OfficeNamespaces.FO_NS, KEEP_WITH_NEXT, ALWAYS);
                        }

                        attrs.setAttribute(OfficeNamespaces.TABLE_NS, OfficeToken.STYLE_NAME, style.getStyleName());
                    }
                    detailBandProcessingState = DETAIL_SECTION_FIRST_STARTED;
                }
                else if (detailBandProcessingState == DETAIL_SECTION_FIRST_PRINTED)
                {
                    detailBandProcessingState = DETAIL_SECTION_OTHER_STARTED;
                }
            }

            // process the styles as usual
            performStyleProcessing(attrs);
        }

        final String namespace = ReportTargetUtil.getNamespaceFromAttribute(attrs);
        final String elementType = ReportTargetUtil.getElemenTypeFromAttribute(attrs);
        final AttributeList attrList = buildAttributeList(attrs);
        xmlWriter.writeTag(namespace, elementType, attrList, XmlWriterSupport.OPEN);
    }

    private boolean isParentKeepTogether()
    {
        PageContext context = getCurrentContext();
        if (context != null)
        {
            context = context.getParent();
            if (context != null)
            {
                return context.getKeepTogether() == PageContext.KEEP_TOGETHER_GROUP;
            }
        }
        return false;
    }

    private boolean isTableMergeActive()
    {
        return getCurrentRole() == ROLE_DETAIL &&
                tableLayoutConfig == TABLE_LAYOUT_SINGLE_DETAIL_TABLE;
    }

    private void openSection()
            throws IOException
    {
        if (isRepeatingSection())
        {
            // repeating sections have other ways of defining columns ..
            return;
        }
        if (getCurrentRole() == ROLE_TEMPLATE ||
                getCurrentRole() == ROLE_SPREADSHEET_PAGE_HEADER ||
                getCurrentRole() == ROLE_SPREADSHEET_PAGE_FOOTER)
        {
            // the template section would break the multi-column stuff and we dont open up sections there
            // anyway ..
            return;
        }

        final PageContext pageContext = getCurrentContext();
        final Integer columnCount = pageContext.getColumnCount();
        if (columnCount != null && !pageContext.isSectionOpen())
        {
            final AttributeList attrs = new AttributeList();
            attrs.setAttribute(OfficeNamespaces.TEXT_NS, OfficeToken.STYLE_NAME, generateSectionStyle(columnCount.intValue()));
            attrs.setAttribute(OfficeNamespaces.TEXT_NS, NAME, sectionNames.generateName("Section"));
            getXmlWriter().writeTag(OfficeNamespaces.TEXT_NS, "section", attrs, XmlWriterSupport.OPEN);

            pageContext.setSectionOpen(true);
        }

    }

    protected void startReportSection(final AttributeMap attrs, final int role)
            throws IOException, DataSourceException, ReportProcessingException
    {
        sectionHeight = new LengthCalculator();
        if (role == OfficeDocumentReportTarget.ROLE_TEMPLATE ||
                role == OfficeDocumentReportTarget.ROLE_SPREADSHEET_PAGE_HEADER ||
                role == OfficeDocumentReportTarget.ROLE_SPREADSHEET_PAGE_FOOTER)
        {
            // Start buffering with an dummy styles-collection, so that the global styles dont get polluted ..
            startBuffering(new OfficeStylesCollection(), true);
        }
        else if (role == OfficeDocumentReportTarget.ROLE_PAGE_HEADER)
        {
            startBuffering(getGlobalStylesCollection(), true);
            pageHeaderOnReportHeader = PageSection.isPrintWithReportHeader(attrs);
            pageHeaderOnReportFooter = PageSection.isPrintWithReportFooter(attrs);
        }
        else if (role == OfficeDocumentReportTarget.ROLE_PAGE_FOOTER)
        {
            startBuffering(getGlobalStylesCollection(), true);
            pageFooterOnReportHeader = PageSection.isPrintWithReportHeader(attrs);
            pageFooterOnReportFooter = PageSection.isPrintWithReportFooter(attrs);
        }
        else if (role == OfficeDocumentReportTarget.ROLE_REPEATING_GROUP_HEADER || role == OfficeDocumentReportTarget.ROLE_REPEATING_GROUP_FOOTER)
        {
            startBuffering(getGlobalStylesCollection(), true);
        }
        else if (role == OfficeDocumentReportTarget.ROLE_VARIABLES)
        {
            startBuffering(getGlobalStylesCollection(), false);
        }
        else
        {
            contentProcessingState = TextRawReportTarget.CP_FIRST_TABLE;
            if (role == OfficeDocumentReportTarget.ROLE_GROUP_HEADER || role == OfficeDocumentReportTarget.ROLE_GROUP_FOOTER)
            {
                // if we have a repeating header, then skip the first one ..
                // if this is a repeating footer, skip the last one. This means,
                // we have to buffer all group footers and wait for the next section..
                startBuffering(getContentStylesCollection(), true);
            }

            if (role != OfficeDocumentReportTarget.ROLE_DETAIL)
            {
                // reset the detail-state. The flag will be updated on startTable and endOther(Table) if the
                // current role is ROLE_DETAIL
                detailBandProcessingState = DETAIL_SECTION_WAIT;
            }
        }
    }

    protected void startGroup(final AttributeMap attrs)
            throws IOException, DataSourceException, ReportProcessingException
    {
        super.startGroup(attrs);
        final PageContext pageContext = new PageContext(getCurrentContext());
        activePageContext.push(pageContext);

        final Object resetPageNumber = attrs.getAttribute(OfficeNamespaces.OOREPORT_NS, "reset-page-number");
        if (OfficeToken.TRUE.equals(resetPageNumber))
        {
            setPagebreakDefinition(new PageBreakDefinition(true));
        }

        final Object keepTogether = attrs.getAttribute(OfficeNamespaces.OOREPORT_NS, KEEP_TOGETHER);
        if ("whole-group".equals(keepTogether))
        {
            pageContext.setKeepTogether(PageContext.KEEP_TOGETHER_GROUP);
        }
        else if ("with-first-detail".equals(keepTogether) && pageContext.getKeepTogether() != PageContext.KEEP_TOGETHER_GROUP)
        {
            pageContext.setKeepTogether(PageContext.KEEP_TOGETHER_FIRST_DETAIL);
        }

        final Object columnCountRaw = attrs.getAttribute(OfficeNamespaces.FO_NS, "column-count");
        final Integer colCount = parseInt(columnCountRaw);
        if (colCount != null)
        {
            pageContext.setColumnCount(colCount);
        }

        final Object newColumn = attrs.getAttribute(OfficeNamespaces.OOREPORT_NS, "start-new-column");
        if (OfficeToken.TRUE.equals(newColumn))
        {
            setColumnBreakPending(true);
        }
    }

    protected void startGroupInstance(final AttributeMap attrs)
            throws IOException, DataSourceException, ReportProcessingException
    {
        if (getGroupContext().isGroupWithRepeatingSection())
        {
            setPagebreakDefinition(new PageBreakDefinition(isResetPageNumber()));
        }
    }

    protected void endGroup(final AttributeMap attrs)
            throws IOException, DataSourceException, ReportProcessingException
    {
        if (getGroupContext().isGroupWithRepeatingSection())
        {
            setPagebreakDefinition(new PageBreakDefinition(isResetPageNumber()));
        }

        super.endGroup(attrs);
        finishSection();

        activePageContext.pop();
    }

    private void finishSection()
            throws ReportProcessingException
    {
        final PageContext pageContext = getCurrentContext();
        if (pageContext.isSectionOpen())
        {
            pageContext.setSectionOpen(false);
            try
            {
                getXmlWriter().writeCloseTag();
            }
            catch (IOException e)
            {
                throw new ReportProcessingException("IOError", e);
            }
        }
    }

    protected void endReportSection(final AttributeMap attrs, final int role)
            throws IOException, DataSourceException, ReportProcessingException
    {
        if (role == ROLE_TEMPLATE ||
                role == OfficeDocumentReportTarget.ROLE_SPREADSHEET_PAGE_HEADER ||
                role == OfficeDocumentReportTarget.ROLE_SPREADSHEET_PAGE_FOOTER)
        {
            finishBuffering();
            return;
        }

        final CSSNumericValue result = sectionHeight.getResult();
        if (role == OfficeDocumentReportTarget.ROLE_PAGE_HEADER)
        {
            final PageContext pageContext = getCurrentContext();
            pageContext.setHeader(applyColumnsToPageBand(finishBuffering(), pageContext.getActiveColumns()).getXmlBuffer(), result);
        }
        else if (role == OfficeDocumentReportTarget.ROLE_PAGE_FOOTER)
        {
            final PageContext pageContext = getCurrentContext();
            pageContext.setFooter(applyColumnsToPageBand(finishBuffering(), pageContext.getActiveColumns()).getXmlBuffer(), result);
        }
        else if (role == OfficeDocumentReportTarget.ROLE_REPEATING_GROUP_HEADER)
        {
            final PageContext pageContext = getCurrentContext();
            pageContext.setHeader(applyColumnsToPageBand(finishBuffering(), pageContext.getActiveColumns()).getXmlBuffer(), result);
        }
        else if (role == OfficeDocumentReportTarget.ROLE_REPEATING_GROUP_FOOTER)
        {
            final PageContext pageContext = getCurrentContext();
            pageContext.setFooter(applyColumnsToPageBand(finishBuffering(), pageContext.getActiveColumns()).getXmlBuffer(), result);
        }
        else if (role == OfficeDocumentReportTarget.ROLE_VARIABLES)
        {
            if (variables == null)
            {
                variables = finishBuffering().getXmlBuffer();
            }
            else
            {
                variables += finishBuffering().getXmlBuffer();
            }
        }
        else if (role == OfficeDocumentReportTarget.ROLE_GROUP_HEADER)
        {
            final String headerText = finishBuffering().getXmlBuffer();
            final int iterationCount = getGroupContext().getParent().getIterationCount();
            final boolean repeat = OfficeToken.TRUE.equals(attrs.getAttribute(OfficeNamespaces.OOREPORT_NS, "repeat-section"));
            if (!repeat || iterationCount > 0)
            {
                getXmlWriter().writeText(headerText);
            }
        }
        else if (role == OfficeDocumentReportTarget.ROLE_GROUP_FOOTER)
        {
            final String footerText = finishBuffering().getXmlBuffer();
            // how do we detect whether this is the last group footer?
            getXmlWriter().writeText(footerText);
        }

    }

    public void endReport(final ReportStructureRoot report)
            throws DataSourceException, ReportProcessingException
    {
        super.endReport(report);
        variablesDeclarations = null;

        try
        {
            // Write the settings ..
            final AttributeList rootAttributes = new AttributeList();
            rootAttributes.addNamespaceDeclaration("office", OfficeNamespaces.OFFICE_NS);
            rootAttributes.addNamespaceDeclaration("config", OfficeNamespaces.CONFIG);
            rootAttributes.addNamespaceDeclaration("ooo", OfficeNamespaces.OO2004_NS);
            rootAttributes.setAttribute(OfficeNamespaces.OFFICE_NS, "version", "1.0");
            final OutputStream outputStream = getOutputRepository().createOutputStream("settings.xml", "text/xml");
            final XmlWriter xmlWriter = new XmlWriter(new OutputStreamWriter(outputStream, "UTF-8"), createTagDescription());
            xmlWriter.setAlwaysAddNamespace(true);
            xmlWriter.writeXmlDeclaration("UTF-8");
            xmlWriter.writeTag(OfficeNamespaces.OFFICE_NS, "document-settings", rootAttributes, XmlWriterSupport.OPEN);
            xmlWriter.writeTag(OfficeNamespaces.OFFICE_NS, "settings", XmlWriterSupport.OPEN);
            xmlWriter.writeTag(OfficeNamespaces.CONFIG, "config-item-set", NAME, "ooo:configuration-settings", XmlWriterSupport.OPEN);

            final AttributeList configAttributes = new AttributeList();
            configAttributes.setAttribute(OfficeNamespaces.CONFIG, NAME, "TableRowKeep");
            configAttributes.setAttribute(OfficeNamespaces.CONFIG, "type", "boolean");
            xmlWriter.writeTag(OfficeNamespaces.CONFIG, "config-item", configAttributes, XmlWriterSupport.OPEN);
            xmlWriter.writeText(OfficeToken.TRUE);
            xmlWriter.writeCloseTag();

            xmlWriter.writeCloseTag();
            xmlWriter.writeCloseTag();
            xmlWriter.writeCloseTag();
            xmlWriter.close();

            // now copy the meta.xml
            if (getInputRepository().isReadable("meta.xml"))
            {
                final InputStream inputStream = getInputRepository().createInputStream("meta.xml");
                try
                {
                    final OutputStream outputMetaStream = getOutputRepository().createOutputStream("meta.xml", "text/xml");
                    IOUtils.getInstance().copyStreams(inputStream, outputMetaStream);
                    outputMetaStream.close();
                } finally
                {
                    inputStream.close();
                }
            }
        }
        catch (IOException ioe)
        {
            throw new ReportProcessingException("Failed to write settings document");
        }
    }

    protected void endOther(final AttributeMap attrs)
            throws IOException, DataSourceException, ReportProcessingException
    {
        final String namespace = ReportTargetUtil.getNamespaceFromAttribute(attrs);
        final String elementType = ReportTargetUtil.getElemenTypeFromAttribute(attrs);

        final boolean isInternalNS = ObjectUtilities.equal(JFreeReportInfo.REPORT_NAMESPACE, namespace);
        final boolean isTableNs = ObjectUtilities.equal(OfficeNamespaces.TABLE_NS, namespace);
        if (isTableMergeActive() && detailBandProcessingState == DETAIL_SECTION_OTHER_PRINTED && isTableNs && ObjectUtilities.equal(OfficeToken.TABLE_COLUMNS, elementType))
        {
            finishBuffering();
            return;
        }

        if (isInternalNS && (ObjectUtilities.equal(OfficeToken.IMAGE, elementType) ||
                ObjectUtilities.equal(OfficeToken.OBJECT_OLE, elementType)))
        {
            return;
        }

        final XmlWriter xmlWriter = getXmlWriter();
        if (tableLayoutConfig != TABLE_LAYOUT_VARIABLES_PARAGRAPH &&
                isTableNs && ObjectUtilities.equal(OfficeToken.TABLE_CELL, elementType))
        {
            if (variables != null)
            {
                // This cannot happen as long as the report sections only contain tables. But at some point in the
                // future they will be made of paragraphs, and then we are prepared ..
                //LOGGER.debug("Variables-Section " + variables);
                final String tag;
                if (sectionKeepTogether && expectedTableRowCount > 0)
                {
                    tag = TextRawReportTarget.VARIABLES_HIDDEN_STYLE_WITH_KEEPWNEXT;
                }
                else
                {
                    tag = TextRawReportTarget.VARIABLES_HIDDEN_STYLE_WITHOUT_KEEPWNEXT;
                }
                StyleUtilities.copyStyle(OfficeToken.PARAGRAPH,
                        tag, getStylesCollection(),
                        getGlobalStylesCollection(), getPredefinedStylesCollection());
                xmlWriter.writeTag(OfficeNamespaces.TEXT_NS, OfficeToken.P, OfficeToken.STYLE_NAME,
                        tag, XmlWriterSupport.OPEN);
                xmlWriter.writeText(variables);
                xmlWriter.writeCloseTag();
                variables = null;
            }
        /**
        // Only generate the empty paragraph, if we have to add the keep-together ..
        else if (cellEmpty && expectedTableRowCount > 0 &&
        sectionKeepTogether && !firstCellSeen)
        {
        // we have no variables ..
        StyleUtilities.copyStyle(OfficeToken.PARAGRAPH,
        TextRawReportTarget.VARIABLES_HIDDEN_STYLE_WITH_KEEPWNEXT, getStylesCollection(),
        getGlobalStylesCollection(), getPredefinedStylesCollection());
        xmlWriter.writeTag(OfficeNamespaces.TEXT_NS, OfficeToken.P, OfficeToken.STYLE_NAME,
        TextRawReportTarget.VARIABLES_HIDDEN_STYLE_WITH_KEEPWNEXT, XmlWriterSupport.CLOSE);
        }
         */
        }

        if (isTableNs && (ObjectUtilities.equal(OfficeToken.TABLE_CELL, elementType) || ObjectUtilities.equal(OfficeToken.COVERED_TABLE_CELL, elementType)))
        {
            firstCellSeen = true;
        }
        if (isTableNs && ObjectUtilities.equal(OfficeToken.TABLE, elementType))
        {
            if (getCurrentRole() == ROLE_DETAIL)
            {
                if (!isTableMergeActive())
                {
                    // We do not merge the detail bands, so an ordinary close will do.
                    xmlWriter.writeCloseTag();
                }
                else if (detailBandProcessingState == DETAIL_SECTION_FIRST_STARTED)
                {
                    final int keepTogetherState = getCurrentContext().getKeepTogether();
                    if (keepTogetherState == PageContext.KEEP_TOGETHER_FIRST_DETAIL)
                    {
                        xmlWriter.writeCloseTag();
                        detailBandProcessingState = DETAIL_SECTION_FIRST_PRINTED;
                    }
                    else
                    {
                        detailBandProcessingState = DETAIL_SECTION_OTHER_PRINTED;
                    }
                }
                else if (detailBandProcessingState == DETAIL_SECTION_OTHER_STARTED)
                {
                    detailBandProcessingState = DETAIL_SECTION_OTHER_PRINTED;
                }
            }
            else
            {
                xmlWriter.writeCloseTag();
            }
            if (isSectionPagebreakAfter(attrs))
            {
                setPagebreakDefinition(new PageBreakDefinition(false));
            }
        }
        else
        {
            xmlWriter.writeCloseTag();
        }
    }

    protected void endGroupBody(final AttributeMap attrs)
            throws IOException, DataSourceException, ReportProcessingException
    {
        if (tableLayoutConfig == TABLE_LAYOUT_SINGLE_DETAIL_TABLE && detailBandProcessingState == DETAIL_SECTION_OTHER_PRINTED)
        {
            // closes the table ..
            final XmlWriter xmlWriter = getXmlWriter();
            xmlWriter.writeCloseTag();
            detailBandProcessingState = DETAIL_SECTION_WAIT;
        }

    }

    protected void endContent(final AttributeMap attrs)
            throws IOException, DataSourceException, ReportProcessingException
    {
        finishSection();
        final BufferState bodyText = finishBuffering();
        final XmlWriter writer = getXmlWriter();

        final Map definedMappings = variablesDeclarations.getDefinedMappings();
        if (!definedMappings.isEmpty())
        {
            writer.writeTag(OfficeNamespaces.TEXT_NS, "variable-decls", XmlWriterSupport.OPEN);
            final Iterator mappingsIt = definedMappings.entrySet().iterator();
            while (mappingsIt.hasNext())
            {
                final Map.Entry entry = (Map.Entry) mappingsIt.next();
                final AttributeList entryList = new AttributeList();
                entryList.setAttribute(OfficeNamespaces.TEXT_NS, NAME, (String) entry.getKey());
                entryList.setAttribute(OfficeNamespaces.OFFICE_NS, FormatValueUtility.VALUE_TYPE, (String) entry.getValue());
                writer.writeTag(OfficeNamespaces.TEXT_NS, "variable-decl", entryList, XmlWriterSupport.CLOSE);
            }
            writer.writeCloseTag();
        }

        writer.writeStream(bodyText.getXmlAsReader());
        writer.setLineEmpty(true);
        writer.writeCloseTag();
    }

    public String getExportDescriptor()
    {
        return "raw/" + PentahoReportEngineMetaData.OPENDOCUMENT_TEXT;
    }
}