File: AbstractRenderer.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 (1036 lines) | stat: -rw-r--r-- 35,935 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
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
/**
 * ===========================================
 * 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: AbstractRenderer.java 6489 2008-11-28 14:53:40Z tmorgner $
 * ------------
 * (C) Copyright 2006-2007, by Pentaho Corporation.
 */
package org.jfree.layouting.renderer;

import java.awt.Dimension;
import java.awt.Image;

import org.jfree.layouting.LayoutProcess;
import org.jfree.layouting.State;
import org.jfree.layouting.StateException;
import org.jfree.layouting.LibLayoutBoot;
import org.jfree.layouting.input.style.keys.box.BoxStyleKeys;
import org.jfree.layouting.input.style.keys.line.LineStyleKeys;
import org.jfree.layouting.input.style.keys.positioning.PositioningStyleKeys;
import org.jfree.layouting.input.style.values.CSSFunctionValue;
import org.jfree.layouting.input.style.values.CSSValue;
import org.jfree.layouting.layouter.content.ContentToken;
import org.jfree.layouting.layouter.content.computed.ComputedToken;
import org.jfree.layouting.layouter.content.computed.VariableToken;
import org.jfree.layouting.layouter.content.resolved.ResolvedCounterToken;
import org.jfree.layouting.layouter.content.resolved.ResolvedStringToken;
import org.jfree.layouting.layouter.content.type.GenericType;
import org.jfree.layouting.layouter.content.type.ResourceType;
import org.jfree.layouting.layouter.content.type.TextType;
import org.jfree.layouting.layouter.context.LayoutContext;
import org.jfree.layouting.layouter.context.PageContext;
import org.jfree.layouting.normalizer.content.NormalizationException;
import org.jfree.layouting.output.OutputProcessor;
import org.jfree.layouting.renderer.border.BorderFactory;
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.BoxDefinitionFactory;
import org.jfree.layouting.renderer.model.DefaultBoxDefinitionFactory;
import org.jfree.layouting.renderer.model.InlineRenderBox;
import org.jfree.layouting.renderer.model.MarkerRenderBox;
import org.jfree.layouting.renderer.model.NormalFlowRenderBox;
import org.jfree.layouting.renderer.model.PageAreaRenderBox;
import org.jfree.layouting.renderer.model.ParagraphRenderBox;
import org.jfree.layouting.renderer.model.RenderBox;
import org.jfree.layouting.renderer.model.RenderNode;
import org.jfree.layouting.renderer.model.RenderableReplacedContent;
import org.jfree.layouting.renderer.model.RenderableTextBox;
import org.jfree.layouting.renderer.model.ParagraphPoolBox;
import org.jfree.layouting.renderer.model.page.LogicalPageBox;
import org.jfree.layouting.renderer.model.page.PageGrid;
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.TableRowRenderBox;
import org.jfree.layouting.renderer.model.table.TableSectionRenderBox;
import org.jfree.layouting.renderer.page.RenderPageContext;
import org.jfree.layouting.renderer.process.ValidateModelStep;
import org.jfree.layouting.renderer.process.CheckHibernationLayoutStep;
import org.jfree.layouting.renderer.text.DefaultRenderableTextFactory;
import org.jfree.layouting.renderer.text.RenderableTextFactory;
import org.jfree.layouting.util.geom.StrictDimension;
import org.jfree.layouting.util.geom.StrictGeomUtility;
import org.pentaho.reporting.libraries.fonts.encoding.CodePointBuffer;
import org.pentaho.reporting.libraries.fonts.encoding.manual.Utf16LE;
import org.pentaho.reporting.libraries.base.util.FastStack;
import org.pentaho.reporting.libraries.base.util.WaitingImageObserver;
import org.pentaho.reporting.libraries.resourceloader.ResourceKey;
import org.pentaho.reporting.libraries.resourceloader.factory.drawable.DrawableWrapper;

/**
 * Creation-Date: 16.06.2006, 14:10:40
 *
 * @author Thomas Morgner
 */
public abstract class AbstractRenderer implements Renderer
{
  protected abstract static class RendererState implements State
  {
    private BoxDefinitionFactory boxDefinitionFactory;
    private State pageContext;
    private int bufferLength;
    private LogicalPageBox logicalPageBox;

    private ContentStore elementsStore;
    private ContentStore pendingStore;

    // todo:!
    private FlowContext.FlowContextState[] flowContexts;

    protected RendererState(final AbstractRenderer renderer) throws StateException
    {
      this.boxDefinitionFactory = renderer.boxDefinitionFactory;
      if (renderer.pageContext != null)
      {
        this.pageContext = renderer.pageContext.saveState();
      }

      if (renderer.buffer != null)
      {
        this.bufferLength = renderer.buffer.getData().length;
      }

      if (renderer.logicalPageBox != null)
      {
        this.logicalPageBox = (LogicalPageBox)
            renderer.logicalPageBox.hibernate();
        if (LibLayoutBoot.isAsserationEnabled())
        {
          final CheckHibernationLayoutStep step = new CheckHibernationLayoutStep();
          step.startProcessing(this.logicalPageBox);
        }
      }

      try
      {
        this.elementsStore = (ContentStore) renderer.elementsStore.clone();
        this.pendingStore = (ContentStore) renderer.pendingStore.clone();
      }
      catch (CloneNotSupportedException e)
      {
        throw new StateException();
      }

      final FastStack renderFlowContexts = renderer.flowContexts;
      this.flowContexts = new FlowContext.FlowContextState
          [renderFlowContexts.size()];
      for (int i = 0; i < renderFlowContexts.size(); i++)
      {
        final FlowContext context = (FlowContext) renderFlowContexts.get(i);
        flowContexts[i] = context.saveState();
      }
    }


    protected void fill(final AbstractRenderer renderer,
                        final LayoutProcess layoutProcess) throws StateException
    {
      if (bufferLength > 0)
      {
        renderer.buffer = new CodePointBuffer(bufferLength);
      }

      try
      {
        renderer.elementsStore = (ContentStore) this.elementsStore.clone();
        renderer.pendingStore = (ContentStore) this.pendingStore.clone();
      }
      catch (CloneNotSupportedException e)
      {
        throw new StateException();
      }
      renderer.boxDefinitionFactory = this.boxDefinitionFactory;
      if (pageContext != null)
      {
        renderer.pageContext = (RenderPageContext)
            this.pageContext.restore(layoutProcess);
      }
      if (logicalPageBox != null)
      {
        renderer.logicalPageBox = (LogicalPageBox)
            this.logicalPageBox.derive(true);
      }

      renderer.flowContexts = new FastStack();
      for (int i = 0; i < flowContexts.length; i++)
      {
        final FlowContext.FlowContextState state = flowContexts[i];
        final Object currentFlowId = state.getCurrentFlowId();
        final State textFactoryState = state.getTextFactoryState();
        final RenderableTextFactory textFactory =
            (RenderableTextFactory) textFactoryState.restore(layoutProcess);
        final NormalFlowRenderBox box = (NormalFlowRenderBox)
            renderer.logicalPageBox.findNodeById(currentFlowId);
        if (box == null)
        {
          throw new StateException("No Such normal flow.");
        }
        renderer.flowContexts.push(new FlowContext(textFactory, box));
      }
    }
  }

  // from restore
  private LayoutProcess layoutProcess;
  // statefull ..
  private LogicalPageBox logicalPageBox;
  private ContentStore elementsStore;
  private ContentStore pendingStore;
  private FastStack flowContexts;

  // to be recreated
  private CodePointBuffer buffer;
  // Stateless components ..
  private RenderPageContext pageContext;
  private BoxDefinitionFactory boxDefinitionFactory;
  private Object layoutFailureNodeId;
  private int layoutFailureReason;

  protected AbstractRenderer(final LayoutProcess layoutProcess,
                             final boolean init)
  {
    if (layoutProcess == null)
    {
      throw new NullPointerException();
    }

    this.layoutProcess = layoutProcess;
    this.flowContexts = new FastStack();

    if (init)
    {
      this.elementsStore = new ContentStore();
      this.pendingStore = new ContentStore();
      this.boxDefinitionFactory =
          new DefaultBoxDefinitionFactory(new BorderFactory());
    }
  }

  public LogicalPageBox getLogicalPageBox()
  {
    return logicalPageBox;
  }

  public LayoutProcess getLayoutProcess()
  {
    return layoutProcess;
  }

  public RenderPageContext getRenderPageContext()
  {
    return pageContext;
  }

  public void setLayoutFailureReason
      (final int layoutFailureReason, final Object layoutFailureNodeId)
  {
    this.layoutFailureNodeId = layoutFailureNodeId;
    this.layoutFailureReason = layoutFailureReason;
  }

  public void startedDocument(final PageContext pageContext)
  {
    if (pageContext == null)
    {
      throw new NullPointerException();
    }

    final LayoutProcess layoutProcess = getLayoutProcess();
    final OutputProcessor outputProcessor = layoutProcess.getOutputProcessor();
    outputProcessor.processDocumentMetaData(layoutProcess.getDocumentContext());

    this.pageContext = new RenderPageContext(layoutProcess, pageContext);
    // create the initial pagegrid.
    final PageGrid pageGrid =
        this.pageContext.createPageGrid(this.layoutProcess.getOutputMetaData());

    // initialize the logical page. The logical page needs the page grid,
    // as this contains the hints for the physical page sizes.
    logicalPageBox = new LogicalPageBox(pageGrid);
    logicalPageBox.setPageContext(this.pageContext.getPageContext());


  }

  /**
   * @param instanceId can be null if there is no meaningful instanceid.
   * @throws NormalizationException
   */
  protected final void tryValidateOutput(final Object instanceId)
      throws NormalizationException
  {
    if (isValidatable(instanceId))
    {
      try
      {
        validateOutput();
      }
      catch(IllegalStateException e)
      {
        e.printStackTrace();
        //validateOutput();
        ModelPrinter.print(logicalPageBox);
      }
    }
  }

  private boolean isValidatable(final Object instanceId)
  {
    if (layoutFailureReason == ValidateModelStep.BOX_MUST_BE_CLOSED)
    {
      if (instanceId != layoutFailureNodeId)
      {
//        Log.debug("Validation impossible: waiting for close event" +
//            " on node " +
//            logicalPageBox.findNodeById(layoutFailureNodeId));
        return false;
      }

      layoutFailureReason = ValidateModelStep.LAYOUT_OK;
      layoutFailureNodeId = null;
    }
    return true;
  }

  protected abstract void validateOutput() throws NormalizationException;

  protected RenderBox getInsertationPoint()
  {
    final FlowContext context = (FlowContext) flowContexts.peek();
    final NormalFlowRenderBox currentFlow = context.getCurrentFlow();
    if (currentFlow == null)
    {
      throw new IllegalStateException("There is no flow active at the moment.");
    }
    return currentFlow.getInsertationPoint();
  }

  protected boolean isProcessingNormalFlow()
  {
    return this.flowContexts.size() <= 1;
  }

  public void startedFlow(final LayoutContext context)
      throws NormalizationException
  {
    this.pageContext = pageContext.update(context);

    if (logicalPageBox.isNormalFlowActive() == false)
    {
      // this is the first (the normal) flow. A document always starts
      // with a start-document and then a start-flow event.
      logicalPageBox.setNormalFlowActive(true);
      final DefaultRenderableTextFactory textFactory = new DefaultRenderableTextFactory(layoutProcess);
      textFactory.startText();

      final FlowContext flowContext = new FlowContext
          (textFactory, logicalPageBox.getNormalFlow());

      flowContexts.push(flowContext);
    }
    else
    {
      // now check, what flow you are. A flow-top?
      // position: running(header); New headers replace old ones.
      // how to differentiate that (so that style-definitions are not that
      // complicated.

      // For now, we keep it simple. running(header) means go to header
      final CSSValue value = context.getValue(PositioningStyleKeys.POSITION);
      if (value instanceof CSSFunctionValue)
      {
        final CSSFunctionValue fnvalue = (CSSFunctionValue) value;
        final CSSValue[] parameters = fnvalue.getParameters();
        if (parameters.length > 0)
        {
          // Todo: Oh, thats so primitive ...
          final CSSValue targetValue = parameters[0];
          startHeaderFlow(targetValue.getCSSText(), context);
          return;
        }
      }

      // The receiving element would define the content property as
      // 'content: elements(header)'

      // an ordinary flow?
      final BoxDefinition contentRoot =
          boxDefinitionFactory.createBlockBoxDefinition
              (context, layoutProcess.getOutputMetaData());

      final NormalFlowRenderBox newFlow = new NormalFlowRenderBox(contentRoot);
      newFlow.appyStyle(context, layoutProcess.getOutputMetaData());
      newFlow.setPageContext(pageContext.getPageContext());

      final RenderBox currentBox = getInsertationPoint();
      currentBox.addChild(newFlow.getPlaceHolder());
      currentBox.getNormalFlow().addFlow(newFlow);

      final DefaultRenderableTextFactory textFactory =
          new DefaultRenderableTextFactory(layoutProcess);
      textFactory.startText();

      final FlowContext flowContext = new FlowContext
          (textFactory, newFlow);

      flowContexts.push(flowContext);
    }
  }

  private void startHeaderFlow(final String target, final LayoutContext context)
  {
    final BoxDefinition contentRoot =
        boxDefinitionFactory.createBlockBoxDefinition
            (context, layoutProcess.getOutputMetaData());

    final NormalFlowRenderBox newFlow = new NormalFlowRenderBox(contentRoot);
    newFlow.appyStyle(context, layoutProcess.getOutputMetaData());
    newFlow.setPageContext(pageContext.getPageContext());

    if ("header".equals(target))
    {
      final PageAreaRenderBox headerArea = logicalPageBox.getHeaderArea();
      headerArea.clear();
      headerArea.addChild(newFlow);
    }
    else if ("footer".equals(target))
    {
      final PageAreaRenderBox footerArea = logicalPageBox.getFooterArea();
      footerArea.clear();
      footerArea.addChild(newFlow);
    }

    final DefaultRenderableTextFactory textFactory =
        new DefaultRenderableTextFactory(layoutProcess);
    textFactory.startText();

    final FlowContext flowContext = new FlowContext
        (textFactory, newFlow);

    flowContexts.push(flowContext);
  }

  public void startedTable(final LayoutContext context)
      throws NormalizationException
  {
    final RenderableTextFactory textFactory = getCurrentTextFactory();
    getInsertationPoint().addChilds(textFactory.finishText());

    textFactory.startText();

    final BoxDefinition definition =
        boxDefinitionFactory.createBlockBoxDefinition
            (context, layoutProcess.getOutputMetaData());
    this.pageContext = pageContext.update(context);

    final TableRenderBox tableRenderBox =
        new TableRenderBox(definition);
    tableRenderBox.appyStyle(context, layoutProcess.getOutputMetaData());
    tableRenderBox.setPageContext(pageContext.getPageContext());

    getInsertationPoint().addChild(tableRenderBox);

    // tryValidateOutput();

  }

  private RenderableTextFactory getCurrentTextFactory()
  {
    final FlowContext context = (FlowContext) flowContexts.peek();
    return context.getTextFactory();
  }

  public void startedTableColumnGroup(final LayoutContext context)
      throws NormalizationException
  {
    final RenderableTextFactory textFactory = getCurrentTextFactory();
    getInsertationPoint().addChilds(textFactory.finishText());

    textFactory.startText();

    this.pageContext = pageContext.update(context);

    final BoxDefinition definition =
        boxDefinitionFactory.createBlockBoxDefinition
            (context, layoutProcess.getOutputMetaData());
    final TableColumnGroupNode columnGroupNode = new TableColumnGroupNode(definition);
    columnGroupNode.appyStyle(context, layoutProcess.getOutputMetaData());
    getInsertationPoint().addChild(columnGroupNode);

    // tryValidateOutput();

  }

  public void startedTableColumn(final LayoutContext context)
      throws NormalizationException
  {
    final RenderableTextFactory textFactory = getCurrentTextFactory();
    getInsertationPoint().addChilds(textFactory.finishText());

    textFactory.startText();

    this.pageContext = pageContext.update(context);

    final BoxDefinition definition =
        boxDefinitionFactory.createBlockBoxDefinition
            (context, layoutProcess.getOutputMetaData());
    final TableColumnNode columnGroupNode = new TableColumnNode(definition, context);
    getInsertationPoint().addChild(columnGroupNode);

    // tryValidateOutput();

  }

  public void startedTableSection(final LayoutContext context)
      throws NormalizationException
  {
    final RenderableTextFactory textFactory = getCurrentTextFactory();
    getInsertationPoint().addChilds(textFactory.finishText());

    textFactory.startText();

    this.pageContext = pageContext.update(context);

    final BoxDefinition definition =
        boxDefinitionFactory.createBlockBoxDefinition
            (context, layoutProcess.getOutputMetaData());
    final TableSectionRenderBox tableRenderBox =
        new TableSectionRenderBox(definition);
    tableRenderBox.appyStyle(context, layoutProcess.getOutputMetaData());
    tableRenderBox.setPageContext(pageContext.getPageContext());
    getInsertationPoint().addChild(tableRenderBox);

    // tryValidateOutput();

  }

  public void startedTableRow(final LayoutContext context)
      throws NormalizationException
  {
    final RenderableTextFactory textFactory = getCurrentTextFactory();
    getInsertationPoint().addChilds(textFactory.finishText());

    textFactory.startText();

    this.pageContext = pageContext.update(context);

    final BoxDefinition definition =
        boxDefinitionFactory.createBlockBoxDefinition
            (context, layoutProcess.getOutputMetaData());
    final TableRowRenderBox tableRenderBox = new TableRowRenderBox(definition, false);
    tableRenderBox.appyStyle(context, layoutProcess.getOutputMetaData());
    tableRenderBox.setPageContext(pageContext.getPageContext());
    getInsertationPoint().addChild(tableRenderBox);

    // tryValidateOutput();

  }

  public void startedTableCell(final LayoutContext context)
      throws NormalizationException
  {
    final RenderableTextFactory textFactory = getCurrentTextFactory();
    getInsertationPoint().addChilds(textFactory.finishText());

    textFactory.startText();

    this.pageContext = pageContext.update(context);

    final BoxDefinition definition =
        boxDefinitionFactory.createBlockBoxDefinition
            (context, layoutProcess.getOutputMetaData());
    final TableCellRenderBox tableRenderBox =
        new TableCellRenderBox(definition);
    tableRenderBox.setPageContext(pageContext.getPageContext());
    tableRenderBox.appyStyle(context, layoutProcess.getOutputMetaData());

    getInsertationPoint().addChild(tableRenderBox);

    // tryValidateOutput();

  }

  public void startedBlock(final LayoutContext context)
      throws NormalizationException
  {
    final RenderableTextFactory textFactory = getCurrentTextFactory();
    getInsertationPoint().addChilds(textFactory.finishText());

    textFactory.startText();

    this.pageContext = pageContext.update(context);

    final BoxDefinition definition =
        boxDefinitionFactory.createBlockBoxDefinition
            (context, layoutProcess.getOutputMetaData());

    final BlockRenderBox blockBox = new BlockRenderBox(definition);
    blockBox.appyStyle(context, layoutProcess.getOutputMetaData());
    blockBox.setPageContext(pageContext.getPageContext());
    getInsertationPoint().addChild(blockBox);

    // tryValidateOutput(blockBox.getInstanceId());
  }

  public void startedMarker(final LayoutContext context)
      throws NormalizationException
  {
    final RenderableTextFactory textFactory = getCurrentTextFactory();
    getInsertationPoint().addChilds(textFactory.finishText());

    textFactory.startText();

    this.pageContext = pageContext.update(context);

    final BoxDefinition definition =
        boxDefinitionFactory.createInlineBoxDefinition
            (context, layoutProcess.getOutputMetaData());
    final MarkerRenderBox markerBox = new MarkerRenderBox(definition);
    markerBox.appyStyle(context, layoutProcess.getOutputMetaData());
    markerBox.setPageContext(pageContext.getPageContext());
    getInsertationPoint().addChild(markerBox);

    // tryValidateOutput();
  }

  public void startedRootInline(final LayoutContext context)
      throws NormalizationException
  {
    final RenderableTextFactory textFactory = getCurrentTextFactory();
    getInsertationPoint().addChilds(textFactory.finishText());
    textFactory.startText();

    this.pageContext = pageContext.update(context);

    final BoxDefinition definition =
        boxDefinitionFactory.createBlockBoxDefinition
            (context, layoutProcess.getOutputMetaData());
    final ParagraphRenderBox paragraphBox =
        new ParagraphRenderBox(definition);
    paragraphBox.appyStyle(context, layoutProcess.getOutputMetaData());
    paragraphBox.setPageContext(pageContext.getPageContext());

    final RenderBox insertationPoint = getInsertationPoint();
    insertationPoint.addChild(paragraphBox);

    // tryValidateOutput();
  }

  public void startedInline(final LayoutContext context)
      throws NormalizationException
  {
    final RenderableTextFactory textFactory = getCurrentTextFactory();
    getInsertationPoint().addChilds(textFactory.finishText());

    this.pageContext = pageContext.update(context);

    final BoxDefinition definition =
        boxDefinitionFactory.createInlineBoxDefinition
            (context, layoutProcess.getOutputMetaData());
    final InlineRenderBox inlineBox = new InlineRenderBox(definition);
    inlineBox.appyStyle(context, layoutProcess.getOutputMetaData());
    inlineBox.setPageContext(pageContext.getPageContext());

    final RenderBox insertationPoint = getInsertationPoint();
    insertationPoint.addChild(inlineBox);

    // tryValidateOutput();
  }

  public void addContent(final LayoutContext context,
                         final ContentToken content)
      throws NormalizationException
  {
    final RenderableTextFactory textFactory = getCurrentTextFactory();
    if (content instanceof GenericType)
    {
      final GenericType generic = (GenericType) content;
      ResourceKey source = null;
      if (content instanceof ResourceType)
      {
        final ResourceType resourceType = (ResourceType) content;
        source = resourceType.getContent().getSource();
      }

      final Object raw = generic.getRaw();
      if (raw instanceof Image)
      {
        final RenderableReplacedContent replacedContent =
            createImage((Image) raw, source, context);
        if (replacedContent != null)
        {
          replacedContent.appyStyle(context, layoutProcess.getOutputMetaData());

          getInsertationPoint().addChilds(textFactory.finishText());
          getInsertationPoint().addChild(replacedContent);
          tryValidateOutput(null);
          return;
        }
      }
      else if (raw instanceof DrawableWrapper)
      {
        final RenderableReplacedContent replacedContent =
            createDrawable((DrawableWrapper) raw, source, context);
        if (replacedContent != null)
        {
          replacedContent.appyStyle(context, layoutProcess.getOutputMetaData());

          getInsertationPoint().addChilds(textFactory.finishText());
          getInsertationPoint().addChild(replacedContent);
          tryValidateOutput(null);
          return;
        }
      }
    }


    if (content instanceof ResolvedCounterToken)
    {
      final ResolvedCounterToken resolvedToken = (ResolvedCounterToken) content;
      if (isProcessingNormalFlow() == false)
      {
        getInsertationPoint().addChilds(textFactory.finishText());
        try
        {
          final RenderableTextBox token = new RenderableTextBox
              (textFactory.saveState(), resolvedToken, context);
          token.appyStyle(context, getLayoutProcess().getOutputMetaData());
          getInsertationPoint().addChild(token);
          token.close();
          tryValidateOutput(null);
          return;
        }
        catch (StateException se)
        {
          // Should not happen ..
          throw new NormalizationException("State failed.", se);
        }
      }
    }

    if (context instanceof ResolvedStringToken)
    {
      final ResolvedStringToken resolvedToken = (ResolvedStringToken) context;
      final ComputedToken parent = resolvedToken.getParent();
      // todo: The test should be: isProcessingPageFlow()
      if (parent instanceof VariableToken && isProcessingNormalFlow() == false)
      {
        getInsertationPoint().addChilds(textFactory.finishText());
        try
        {
          final RenderableTextBox token = new RenderableTextBox
              (textFactory.saveState(), resolvedToken, context);
          token.appyStyle(context, getLayoutProcess().getOutputMetaData());
          getInsertationPoint().addChild(token);
          token.close();
          tryValidateOutput(null);
          return;
        }
        catch (StateException se)
        {
          // Should not happen ..
          throw new NormalizationException("State failed.", se);
        }
      }
    }

    if (content instanceof TextType)
    {
      final TextType textRaw = (TextType) content;
      final String textStr = textRaw.getText();

      final RenderNode[] text = createText(textStr, context);
      if (text.length == 0)
      {
        return;
      }

      final RenderBox insertationPoint = getInsertationPoint();
      insertationPoint.addChilds(text);
      tryValidateOutput(null);
    }
  }

  private RenderNode[] createText(final String str,
                                  final LayoutContext context)
  {
    if (buffer != null)
    {
      buffer.setCursor(0);
    }
    buffer = Utf16LE.getInstance().decodeString(str, buffer);
    final int[] data = buffer.getBuffer();

    final RenderableTextFactory textFactory = getCurrentTextFactory();
    return textFactory.createText(data, 0, buffer.getLength(), context);
  }

  private RenderableReplacedContent createImage(final Image image,
                                                final ResourceKey source,
                                                final LayoutContext context)
  {
    final WaitingImageObserver wobs = new WaitingImageObserver(image);
    wobs.waitImageLoaded();
    if (wobs.isError())
    {
      return null;
    }

    final CSSValue widthVal = context.getValue(BoxStyleKeys.WIDTH);
    final RenderLength width = DefaultBoxDefinitionFactory.computeWidth
        (widthVal, context, layoutProcess.getOutputMetaData(), true, false);

    final CSSValue heightVal = context.getValue(BoxStyleKeys.HEIGHT);
    final RenderLength height = DefaultBoxDefinitionFactory.computeWidth
        (heightVal, context, layoutProcess.getOutputMetaData(), true, false);
    final StrictDimension dims = StrictGeomUtility.createDimension
        (image.getWidth(null), image.getHeight(null));
    final CSSValue valign =
        context.getValue(LineStyleKeys.VERTICAL_ALIGN);
    return new RenderableReplacedContent(image, source, dims, width, height, valign);
  }

  private RenderableReplacedContent createDrawable(final DrawableWrapper image,
                                                   final ResourceKey source,
                                                   final LayoutContext context)
  {
    final StrictDimension dims = new StrictDimension();

    final Dimension preferredSize = image.getPreferredSize();
    if (preferredSize != null)
    {
      dims.setWidth(StrictGeomUtility.toInternalValue(preferredSize.getWidth()));
      dims.setHeight(StrictGeomUtility.toInternalValue(preferredSize.getHeight()));
    }

    final CSSValue widthVal = context.getValue(BoxStyleKeys.WIDTH);
    final RenderLength width = DefaultBoxDefinitionFactory.computeWidth
        (widthVal, context, layoutProcess.getOutputMetaData(), true, false);

    final CSSValue heightVal = context.getValue(BoxStyleKeys.HEIGHT);
    final RenderLength height = DefaultBoxDefinitionFactory.computeWidth
        (heightVal, context, layoutProcess.getOutputMetaData(), true, false);

    final CSSValue valign =
        context.getValue(LineStyleKeys.VERTICAL_ALIGN);
    return new RenderableReplacedContent(image, source, dims, width, height, valign);
  }

  public void finishedInline() throws NormalizationException
  {
    final RenderBox insertationPoint = getInsertationPoint();
    final RenderableTextFactory textFactory = getCurrentTextFactory();
    final RenderNode[] nodes = textFactory.finishText();
    insertationPoint.addChilds(nodes);
    insertationPoint.close();
    // currentBox = (RenderBox) currentBox.getParent();
    tryValidateOutput(insertationPoint.getInstanceId());
  }

  public void finishedRootInline() throws NormalizationException
  {
    final RenderBox insertationPoint = getInsertationPoint();
    if (insertationPoint instanceof ParagraphPoolBox == false)
    {
      getInsertationPoint();
      throw new IllegalStateException
          ("Assertation: A rootInline must call close on a pool box");
    }

    final RenderableTextFactory textFactory = getCurrentTextFactory();
    final RenderNode[] nodes = textFactory.finishText();
    insertationPoint.addChilds(nodes);
    insertationPoint.close();

    tryValidateOutput(insertationPoint.getInstanceId());
  }

  public void finishedMarker() throws NormalizationException
  {
    final RenderBox insertationPoint = getInsertationPoint();
    final RenderableTextFactory textFactory = getCurrentTextFactory();
    final RenderNode[] nodes = textFactory.finishText();
    insertationPoint.addChilds(nodes);

    insertationPoint.close();
    tryValidateOutput(insertationPoint.getInstanceId());
  }

  public void finishedBlock() throws NormalizationException
  {
    final RenderBox insertationPoint = getInsertationPoint();
    final RenderableTextFactory textFactory = getCurrentTextFactory();
    insertationPoint.addChilds(textFactory.finishText());
    insertationPoint.close();
    tryValidateOutput(insertationPoint.getInstanceId());
  }

  public void finishedTableCell() throws NormalizationException
  {
    final RenderBox insertationPoint = getInsertationPoint();
    final RenderableTextFactory textFactory = getCurrentTextFactory();
    insertationPoint.addChilds(textFactory.finishText());
    insertationPoint.close();

    // A table cell is always inside a table row - and that one must be closed
    // before the layouting can continue ..

    // Update the validation tracker; but do not validate...
    isValidatable(insertationPoint);

  }

  public void finishedTableRow() throws NormalizationException
  {
    final RenderBox insertationPoint = getInsertationPoint();
    final RenderableTextFactory textFactory = getCurrentTextFactory();
    insertationPoint.addChilds(textFactory.finishText());
    insertationPoint.close();
    tryValidateOutput(insertationPoint.getInstanceId());
  }

  public void finishedTableSection() throws NormalizationException
  {
    final RenderBox insertationPoint = getInsertationPoint();
    final RenderableTextFactory textFactory = getCurrentTextFactory();
    insertationPoint.addChilds(textFactory.finishText());
    insertationPoint.close();
    tryValidateOutput(insertationPoint.getInstanceId());
  }

  public void finishedTableColumnGroup() throws NormalizationException
  {
    final RenderBox insertationPoint = getInsertationPoint();
    final RenderableTextFactory textFactory = getCurrentTextFactory();
    insertationPoint.addChilds(textFactory.finishText());
    insertationPoint.close();
    // Table Col-groups have no influence on the layout ..
    // tryValidateOutput();
  }

  public void finishedTableColumn() throws NormalizationException
  {
    final RenderBox insertationPoint = getInsertationPoint();
    final RenderableTextFactory textFactory = getCurrentTextFactory();
    insertationPoint.addChilds(textFactory.finishText());
    // tryValidateOutput();
  }

  public void finishedTable() throws NormalizationException
  {
    final RenderBox insertationPoint = getInsertationPoint();
    final RenderableTextFactory textFactory = getCurrentTextFactory();
    insertationPoint.addChilds(textFactory.finishText());
    insertationPoint.close();

    tryValidateOutput(insertationPoint.getInstanceId());
  }

  public void finishedFlow() throws NormalizationException
  {
    final RenderBox insertationPoint = getInsertationPoint();
    final RenderableTextFactory textFactory = getCurrentTextFactory();
    insertationPoint.addChilds(textFactory.finishText());
    insertationPoint.close();

    flowContexts.pop();

    tryValidateOutput(insertationPoint.getInstanceId());
  }

  public void finishedDocument() throws NormalizationException
  {
    logicalPageBox.close();
    tryValidateOutput(logicalPageBox.getInstanceId());
    //validateOutput();
    // At this point, we should have performed the necessary output.

    // Ok, lets play a little bit
    // todo: This is the end of the document, we should do some smarter things
    // here.
  }

  public RenderPageContext getPageContext()
  {
    return pageContext;
  }

  public void handlePageBreak(final PageContext pageContext)
  {
    if (pageContext == null)
    {
      throw new NullPointerException();
    }

    this.pageContext = this.pageContext.update
        (pageContext, layoutProcess.getOutputProcessor());
    final PageGrid pageGrid =
        this.pageContext.createPageGrid(layoutProcess.getOutputMetaData());

    this.pendingStore = (ContentStore) pendingStore.derive();
    this.elementsStore = (ContentStore) elementsStore.derive();
    this.logicalPageBox.updatePageArea(pageGrid);
  }

  public void startedPassThrough(final LayoutContext context)
  {

  }

  public void addPassThroughContent(final LayoutContext context,
                                    final ContentToken content)
  {

  }

  public void finishedPassThrough()
  {

  }


  public void startedTableCaption(final LayoutContext context)
      throws NormalizationException
  {

  }

  public void finishedTableCaption() throws NormalizationException
  {

  }
}