File: TableValidationStep.java

package info (click to toggle)
liblayout 0.2.10-5
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 5,332 kB
  • sloc: java: 51,125; xml: 138; makefile: 17
file content (656 lines) | stat: -rw-r--r-- 22,591 bytes parent folder | download | duplicates (4)
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
/**
 * ===========================================
 * LibLayout : a free Java layouting library
 * ===========================================
 *
 * Project Info:  http://reporting.pentaho.org/liblayout/
 *
 * (C) Copyright 2006-2007, by Pentaho Corporation and Contributors.
 *
 * This library is free software; you can redistribute it and/or modify it under the terms
 * of the GNU Lesser General Public License as published by the Free Software Foundation;
 * either version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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 for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along with this
 * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 * [Java is a trademark or registered trademark of Sun Microsystems, Inc.
 * in the United States and other countries.]
 *
 * ------------
 * $Id: TableValidationStep.java 6489 2008-11-28 14:53:40Z tmorgner $
 * ------------
 * (C) Copyright 2006-2007, by Pentaho Corporation.
 */
package org.jfree.layouting.renderer.process;

import org.jfree.layouting.renderer.border.Border;
import org.jfree.layouting.renderer.border.RenderLength;
import org.jfree.layouting.renderer.model.BlockRenderBox;
import org.jfree.layouting.renderer.model.BoxDefinition;
import org.jfree.layouting.renderer.model.EmptyBoxDefinition;
import org.jfree.layouting.renderer.model.RenderNode;
import org.jfree.layouting.renderer.model.page.LogicalPageBox;
import org.jfree.layouting.renderer.model.table.TableCellRenderBox;
import org.jfree.layouting.renderer.model.table.TableColumnGroupNode;
import org.jfree.layouting.renderer.model.table.TableColumnNode;
import org.jfree.layouting.renderer.model.table.TableRenderBox;
import org.jfree.layouting.renderer.model.table.TableRowInfoStructure;
import org.jfree.layouting.renderer.model.table.TableRowRenderBox;
import org.jfree.layouting.renderer.model.table.TableSectionRenderBox;
import org.jfree.layouting.renderer.model.table.cells.ConflictingCell;
import org.jfree.layouting.renderer.model.table.cells.DataCell;
import org.jfree.layouting.renderer.model.table.cells.PlaceHolderCell;
import org.jfree.layouting.renderer.model.table.cells.TableCell;
import org.jfree.layouting.renderer.model.table.cols.TableColumn;
import org.jfree.layouting.renderer.model.table.cols.TableColumnGroup;
import org.jfree.layouting.renderer.model.table.cols.TableColumnModel;
import org.jfree.layouting.renderer.model.table.rows.TableRow;
import org.jfree.layouting.renderer.model.table.rows.TableRowModel;
import org.pentaho.reporting.libraries.base.util.FastStack;

/**
 * Another static processing step which validates the table structure.
 *
 * @author Thomas Morgner
 */
public class TableValidationStep extends IterateStructuralProcessStep
{
  public static class TableInfoStructure
  {
    private TableRenderBox table;
    private TableColumnModel columnModel;
    private int columns;

    public TableInfoStructure(final TableRenderBox table)
    {
      this.table = table;
      this.columnModel = table.getColumnModel();
      this.columns = columnModel.getColumnCount();
    }

    public TableRenderBox getTable()
    {
      return table;
    }

    public TableColumnModel getColumnModel()
    {
      return columnModel;
    }

    public int getColumns()
    {
      return columns;
    }

    public void setColumns(final int columns)
    {
      this.columns = columns;
    }
  }

  private FastStack tableStack;
  private TableInfoStructure currentTable;

  public TableValidationStep()
  {
    tableStack = new FastStack();
  }

  public void validate(final LogicalPageBox box)
  {
    tableStack.clear();
    currentTable = null;
    startProcessing(box);
    if (tableStack.isEmpty() == false)
    {
      throw new IllegalStateException();
    }
  }

  protected boolean startBlockBox(final BlockRenderBox box)
  {
    if (box instanceof TableRenderBox == false)
    {
      return true;
    }

    final TableRenderBox table = (TableRenderBox) box;
    currentTable = new TableInfoStructure(table);
    tableStack.push(currentTable);

    // if the table is not open and has been validated, then ignore it ..
    if (table.isOpen() == false)
    {
      if (table.isStructureValidated() == false)
      {
        validateTable();
        return true;
      }
      // a table may contain sub-tables. Once the table has been closed, we
      // can be sure that all sub-elements (and thus all sub-tables) have been
      // closed as well.
      return false;
    }
    else
    {
      // An open table always needs revalidation ...
      validateTable();
      return true;
    }
  }

  protected void finishBlockBox(final BlockRenderBox box)
  {
    if (box instanceof TableRenderBox)
    {
      currentTable = (TableInfoStructure) tableStack.pop();
    }
  }

  /**
   * We have to check the table as a complex structure. Writing a sequential
   * parser that waits for events to drive by does not work here, as we have to
   * go back and forward all the time ..
   */
  private void validateTable()
  {
    // first step: Check, whether the column model is complete.
    validatePredefinedColumns();
    validateRowStructure();

    final TableRenderBox table = currentTable.getTable();
    if (table.isOpen() == false)
    {
      table.setStructureValidated(true);
    }
  }

  private void validateFinalRows(final TableSectionRenderBox section)
  {
    // check the last row for row-spanning cells ..

    // first, find the last row of the section ..
    RenderNode rowNode = section.getLastChild();
    TableRowRenderBox lastRow = null;
    while (rowNode != null)
    {
      if (rowNode instanceof TableRowRenderBox)
      {
        lastRow = (TableRowRenderBox) rowNode;
        break;
      }
      rowNode = rowNode.getVisiblePrev();
    }

    final TableRowModel rowModel = section.getRowModel();
    // There is no last row - so this sections is empty.
    while (lastRow != null)
    {

      TableRowRenderBox autoGeneratedRow = null;
      TableRowInfoStructure autoRowInfo = null;

      final TableRowInfoStructure rowInfo = lastRow.getRowInfoStructure();
      for (int i = 0; i < rowInfo.getCellCount(); i++)
      {
        // seek row-spanning cells ..
        final TableCell cell = rowInfo.getCellAt(i);
        if (cell.getRowSpan() > 1)
        {
          // that's one, for instance ...
          if (autoGeneratedRow == null)
          {
            autoGeneratedRow =
                    new TableRowRenderBox(EmptyBoxDefinition.getInstance(), true);
            rowModel.addRow(new TableRow());

            autoRowInfo = autoGeneratedRow.getRowInfoStructure();
            for (int emptyCellCnt = 0; emptyCellCnt < i; emptyCellCnt += 1)
            {
              final TableCellRenderBox autoCell =
                      new TableCellRenderBox(EmptyBoxDefinition.getInstance(), true);
              autoCell.close();
              autoCell.setColumnIndex(emptyCellCnt);
              final DataCell dataCell = new DataCell
                  (1, 1, autoCell.getInstanceId());
              autoRowInfo.addCell(dataCell);
              autoGeneratedRow.addChild(autoCell);
            }
          }

          final PlaceHolderCell placeHolder;
          if (cell instanceof DataCell)
          {
            placeHolder = new PlaceHolderCell
                    ((DataCell) cell, cell.getRowSpan() - 1, cell.getColSpan());
          }
          else if (cell instanceof PlaceHolderCell)
          {
            final PlaceHolderCell prevCell = (PlaceHolderCell) cell;
            placeHolder = new PlaceHolderCell
                    (prevCell.getSourceCell(), cell.getRowSpan() - 1, cell.getColSpan());
          }
          else
          {
            throw new IllegalStateException("Unexpected cell type.");
          }
          autoRowInfo.addCell(placeHolder);
        }
        else if (autoGeneratedRow != null)
        {
          // only add, if the auto-row-box has been already generated ..
          // this prevents the generation of totally empty rows ..
          final TableCellRenderBox autoCell =
                  new TableCellRenderBox(EmptyBoxDefinition.getInstance(), true);
          autoCell.close();
          autoCell.setColumnIndex(i);
          final DataCell dataCell = new DataCell
              (1, 1, autoCell.getInstanceId());
          autoRowInfo.addCell(dataCell);
          autoGeneratedRow.addChild(autoCell);
        }
      }

      if (autoGeneratedRow != null)
      {
        autoGeneratedRow.close();
        autoRowInfo.setValidationDone(true);
        section.addGeneratedChild(autoGeneratedRow);
      }

      // no matter what we do, this one can never generate new columns;
      // it only continues existing ones ..
      lastRow = autoGeneratedRow;
    }
  }

  private void validateRowStructure()
  {
    // check all the newly closed rows and look at their number of columns
    // (cache that one for faster access)
    final TableRenderBox table = currentTable.getTable();
    if (table.isPredefinedColumnsValidated() == false)
    {
      // the predefined columns must be validated first ...
      return;
    }

    final TableColumnModel columnModel = currentTable.getColumnModel();
    // ok, the real work starts here. Forward-Traverse the table by its table-
    // sections.
    RenderNode node = table.getFirstChild();
    while (node != null)
    {
      if (node instanceof TableSectionRenderBox == false)
      {
        node = node.getNext();
        continue;
      }
      // OK; nice we are done. All other column definitions will be ignored
      final TableSectionRenderBox section = (TableSectionRenderBox) node;

      if (section.isStructureValidated() == false)
      {
        // we start with an empty prev-struct; that signals that there are no
        // spanned cells in a first row.
        TableRowInfoStructure prevInfoStruct =
                new TableRowInfoStructure();
        RenderNode rowNode = section.getFirstChild();
        while (rowNode != null)
        {
          if (rowNode.isOpen())
          {
            throw new IllegalStateException
                    ("An open row cannot be part of a layoutable model.");
          }

          // OK, we got a non open row. Now we traverse through the table from
          // top to bottom building the validated row model.
          if (rowNode instanceof TableRowRenderBox == false)
          {
            rowNode = rowNode.getNext();
            continue;
          }

          final TableRowInfoStructure infoStruct =
                  validateRow(section, rowNode, prevInfoStruct);
          final int cellCount = infoStruct.getCellCount();
          if (currentTable.getColumns() < cellCount)
          {
            currentTable.setColumns(cellCount);
          }
          // And finally ... add the new columns to the model ..
          while (cellCount > columnModel.getColumnCount())
          {
            columnModel.addAutoColumn();
          }

          rowNode = rowNode.getNext();
          prevInfoStruct = infoStruct;
        }

        if (section.isOpen() == false)
        {
          // when the section has been closed, we can stop the revalidation ...
          validateFinalRows(section);
          section.setStructureValidated(true);
        }
      }

      node = node.getNext();
    }
  }

  private TableRowInfoStructure validateRow(final TableSectionRenderBox section,
                                            final RenderNode rowNode,
                                            final TableRowInfoStructure prevInfoStruct)
  {
    final TableRowRenderBox rowBox = (TableRowRenderBox) rowNode;
    final TableRowInfoStructure infoStruct =
            rowBox.getRowInfoStructure();

    // As we validate only closed table-rows (and as we do not allow changes once
    // the rows are closed (except for adding auto-cells, of course, which is
    // a necessary evil exception to the rule), we have to do this only once
    // per row ..
    if (infoStruct.isValidationDone())
    {
      return infoStruct;
    }

    RenderNode cellNode = rowBox.getFirstChild();
    int cellPosition = 0;

    while (cellNode != null)
    {
      if (cellNode instanceof TableCellRenderBox == false)
      {
        cellNode = cellNode.getNext();
        continue;
      }

      final TableCellRenderBox cellBox = (TableCellRenderBox) cellNode;
      // we got a cell. Now check our info-struct ..
      if (cellPosition >= prevInfoStruct.getCellCount())
      {
        cellBox.setColumnIndex(cellPosition);
        cellPosition = validateSafeCellPos(cellBox, infoStruct, cellPosition);
      }
      else
      {
        cellPosition = findCellPosition(cellPosition, prevInfoStruct, infoStruct);

        // OK, so we have the insertation point. Lets add our cell there ..
        final int colSpan = cellBox.getColSpan();
        final int rowSpan = cellBox.getRowSpan();
        final DataCell dataCell = new DataCell
            (rowSpan, colSpan, cellBox.getInstanceId());
        infoStruct.addCell(dataCell);
        cellBox.setColumnIndex(cellPosition);

        cellPosition += 1;
        for (int i = 1; i < colSpan; i++)
        {
          // if there's a previous cell at the current position - check it
          // maybe we have a conflicting instruction here

          if (cellPosition < prevInfoStruct.getCellCount())
          {
            final TableCell prevCell = prevInfoStruct.getCellAt(cellPosition);
            if (prevCell.getRowSpan() > 1)
            {
              // thats a conflict. Oh, no!
              final ConflictingCell conflictingCell =
                      new ConflictingCell(dataCell, rowSpan, colSpan - i);
              if (prevCell instanceof ConflictingCell)
              {
                // Oh, there's already a conflict? Coooool...
                // (damn, users, fix your table definitions!)
                final ConflictingCell prevConflictCell = (ConflictingCell) prevCell;
                final int count = prevConflictCell.getConflictingCellCount();
                for (int x = 0; x < count; x++)
                {
                  final PlaceHolderCell phc = prevConflictCell.getConflictingCell(x);
                  if (phc.getRowSpan() > 1)
                  {
                    final PlaceHolderCell placeHolderCell =
                            new PlaceHolderCell(phc.getSourceCell(),
                                    phc.getRowSpan() - 1,
                                    phc.getColSpan());
                    conflictingCell.addConflictingCell(placeHolderCell);
                  }
                }
              }
              else if (prevCell instanceof PlaceHolderCell)
              {
                final PlaceHolderCell prevPHCell = (PlaceHolderCell) prevCell;
                // a new conflict ...
                final PlaceHolderCell placeHolderCell =
                        new PlaceHolderCell(prevPHCell.getSourceCell(),
                                prevCell.getRowSpan() - 1,
                                prevCell.getColSpan());
                conflictingCell.addConflictingCell(placeHolderCell);
              }
              else if (prevCell instanceof DataCell)
              {
                final PlaceHolderCell placeHolderCell =
                        new PlaceHolderCell((DataCell) prevCell,
                                prevCell.getRowSpan() - 1,
                                prevCell.getColSpan());
                conflictingCell.addConflictingCell(placeHolderCell);
              }
              else
              {
                throw new IllegalStateException("Unexpected cell type.");
              }

              infoStruct.addCell(conflictingCell);
            }
            else
            {
              final PlaceHolderCell placeHolderCell =
                      new PlaceHolderCell(dataCell, rowSpan, colSpan - i);
              // a safe position. No conflicts ..
              infoStruct.addCell(placeHolderCell);
            }
          }
          else
          {
            final PlaceHolderCell placeHolderCell =
                    new PlaceHolderCell(dataCell, rowSpan, colSpan - i);
            // no cells means: no conflicts. Thats always the easiest thing
            infoStruct.addCell(placeHolderCell);
          }
          cellPosition += 1;
        }
      }

      cellNode = cellNode.getNext();
    }

    final TableRow row = new TableRow(rowBox.getBorder());
    section.getRowModel().addRow(row);

    infoStruct.setValidationDone(true);

    return infoStruct;
  }

  private int findCellPosition(int cellPosition,
                               final TableRowInfoStructure prevInfoStruct,
                               final TableRowInfoStructure infoStruct)
  {
    // lets search for a proper insertation point.
    // first, skip all row-spanning cellpositions.
    while (cellPosition < prevInfoStruct.getCellCount())
    {
      // look at the prev-cell definition
      final TableCell prevCell = prevInfoStruct.getCellAt(cellPosition);
      if (prevCell.getRowSpan() > 1)
      {
        final DataCell dataCell;
        if (prevCell instanceof DataCell)
        {
          dataCell = (DataCell) prevCell;
        }
        else if (prevCell instanceof PlaceHolderCell)
        {
          final PlaceHolderCell placeHolderCell = (PlaceHolderCell) prevCell;
          dataCell = placeHolderCell.getSourceCell();
        }
        else
        {
          throw new IllegalStateException("Unexpected cell type.");
        }
        // oh no, a spanned cell that conflicts with the current cell.
        // that means: Push the insertation point to the left ..
        // and add placeholders to the current row-info-struct ..
        final int colSpan = prevCell.getColSpan();
        // reduce the rowspan by one, as this is a new row ..
        final int rowSpan = prevCell.getRowSpan() - 1;
        for (int i = 0; i < colSpan; i++)
        {
          final PlaceHolderCell placeHolderCell =
                  new PlaceHolderCell
                          (dataCell, rowSpan, colSpan - i);
          infoStruct.addCell(placeHolderCell);
        }
        cellPosition += prevCell.getColSpan();
      }
      else
      {
        // found a sweet-spot ..
        break;
      }
    }
    return cellPosition;
  }

  private int validateSafeCellPos(final TableCellRenderBox cellBox,
                                  final TableRowInfoStructure infoStruct,
                                  int cellPosition)
  {
    // no such cell at that position. Good, add the plain cell.
    final int colSpan = cellBox.getColSpan();
    final int rowSpan = cellBox.getRowSpan();
    final DataCell dataCell = new DataCell
        (rowSpan, colSpan, cellBox.getInstanceId());
    infoStruct.addCell(dataCell);
    cellPosition += 1;
    for (int i = 1; i < colSpan; i++)
    {
      final PlaceHolderCell placeHolderCell =
              new PlaceHolderCell(dataCell, rowSpan, colSpan - i);
      infoStruct.addCell(placeHolderCell);
      cellPosition += 1;
    }
    return cellPosition;
  }

  private void validatePredefinedColumns()
  {
    final TableRenderBox table = currentTable.getTable();
    if (table.isPredefinedColumnsValidated())
    {
      // all work as been done already ...
      return;
    }

    final TableColumnModel columnModel = table.getColumnModel();

    int colCount = 0;
    RenderNode node = table.getFirstChild();
    while (node != null)
    {
      if (node instanceof TableColumnNode)
      {
        final TableColumnNode columnNode = (TableColumnNode) node;
        if (colCount >= columnModel.getColumnCount())
        {
          // No column exists at that position ..
          final BoxDefinition boxDefinition = columnNode.getBoxDefinition();
          final Border border = boxDefinition.getBorder();
          final RenderLength width = boxDefinition.getPreferredWidth();
          final TableColumn column = new TableColumn(border, width, false);
          final TableColumnGroup group = new TableColumnGroup();
          group.addColumn(column);
          columnModel.addColumnGroup(group);
          colCount += 1;
        }
        else
        {
          // We do not change existing columns. That validation should be the
          // first that checks column definitions, so that state should always
          // be correct.
        }
      }
      else if (node instanceof TableColumnGroupNode)
      {
        final TableColumnGroupNode groupNode = (TableColumnGroupNode) node;

        final boolean newGroupGenerated;
        final TableColumnGroup group;
        if (colCount >= columnModel.getColumnCount())
        {
          group = new TableColumnGroup(groupNode.getBorder());
          newGroupGenerated = true;
        }
        else
        {
          group = columnModel.getGroupForIndex(colCount);
          newGroupGenerated = false;
        }

        RenderNode groupColNode = groupNode.getFirstChild();
        while (groupColNode != null)
        {
          if (groupColNode instanceof TableColumnNode)
          {
            final TableColumnNode columnNode = (TableColumnNode) groupColNode;
            if (colCount >= columnModel.getColumnCount())
            {
              final BoxDefinition boxDefinition = columnNode.getBoxDefinition();
              final Border border = boxDefinition.getBorder();
              final RenderLength width = boxDefinition.getPreferredWidth();
              final TableColumn column = new TableColumn(border, width, false);
              group.addColumn(column);
            }
            else
            {
              colCount += 1;
            }
          }
          else
          {
            // ignore silently ..
          }
          groupColNode = groupColNode.getNext();
        }

        if (newGroupGenerated)
        {
          columnModel.addColumnGroup(group);
          colCount += group.getColumnCount();
        }

      }
      else if (node instanceof TableSectionRenderBox)
      {
        // OK; nice we are done. All other column definitions will be ignored
        table.setPredefinedColumnsValidated(true);
      }
      else
      {
        // ignore ...
      }
      node = node.getNext();
    }
  }
}