File: ContentNormalizer.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 (1053 lines) | stat: -rw-r--r-- 34,039 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
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
/**
 * ===========================================
 * 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: ContentNormalizer.java 6489 2008-11-28 14:53:40Z tmorgner $
 * ------------
 * (C) Copyright 2006-2007, by Pentaho Corporation.
 */
package org.jfree.layouting.normalizer.content;

import java.io.IOException;

import org.jfree.layouting.LayoutProcess;
import org.jfree.layouting.State;
import org.jfree.layouting.StateException;
import org.jfree.layouting.StatefullComponent;
import org.jfree.layouting.input.style.PageAreaType;
import org.jfree.layouting.input.style.PseudoPage;
import org.jfree.layouting.input.style.keys.box.BoxStyleKeys;
import org.jfree.layouting.input.style.keys.box.DisplayRole;
import org.jfree.layouting.input.style.keys.content.ContentStyleKeys;
import org.jfree.layouting.input.style.keys.content.MoveToValues;
import org.jfree.layouting.input.style.values.CSSAutoValue;
import org.jfree.layouting.input.style.values.CSSFunctionValue;
import org.jfree.layouting.input.style.values.CSSStringType;
import org.jfree.layouting.input.style.values.CSSStringValue;
import org.jfree.layouting.input.style.values.CSSValue;
import org.jfree.layouting.input.style.values.CSSValueList;
import org.jfree.layouting.layouter.content.ContentToken;
import org.jfree.layouting.layouter.content.computed.CloseQuoteToken;
import org.jfree.layouting.layouter.content.computed.ComputedToken;
import org.jfree.layouting.layouter.content.computed.ContentsToken;
import org.jfree.layouting.layouter.content.computed.CounterToken;
import org.jfree.layouting.layouter.content.computed.CountersToken;
import org.jfree.layouting.layouter.content.computed.OpenQuoteToken;
import org.jfree.layouting.layouter.content.computed.VariableToken;
import org.jfree.layouting.layouter.content.resolved.ResolvedCounterToken;
import org.jfree.layouting.layouter.content.resolved.ResolvedCountersToken;
import org.jfree.layouting.layouter.content.resolved.ResolvedStringToken;
import org.jfree.layouting.layouter.content.statics.StaticTextToken;
import org.jfree.layouting.layouter.context.ContentSpecification;
import org.jfree.layouting.layouter.context.ContextId;
import org.jfree.layouting.layouter.context.DefaultLayoutContext;
import org.jfree.layouting.layouter.context.DefaultPageContext;
import org.jfree.layouting.layouter.context.LayoutContext;
import org.jfree.layouting.layouter.context.LayoutStyle;
import org.jfree.layouting.layouter.context.QuotesPair;
import org.jfree.layouting.layouter.model.LayoutElement;
import org.jfree.layouting.layouter.style.resolver.StyleResolver;
import org.jfree.layouting.normalizer.displaymodel.ModelBuilder;
import org.jfree.layouting.renderer.Renderer;
import org.jfree.layouting.util.AttributeMap;
import org.jfree.layouting.util.ChainingCallException;
import org.jfree.layouting.util.IntList;

/**
 * This class is responsible for normalizing content from the 'content' style
 * property and for hiding content that has 'display:none' set. The
 * ContentNormalizer also resolves all styles for elements.
 * <p/>
 * Pagebreaks are determined in the model-builder or the layouter. A pagebreak
 * is only activated if it affects a line-box; the normalizer has no information
 * about lineboxes and therefore cannot perform any pagebreak computation at
 * all.
 * <p/>
 * Todo: Content that has been ignored because there was no 'content:contents'
 * definition for it, should have this content moved into the '::alternate'
 * pseudo-element. This one can be used to build footnotes and other fancy
 * stuff.
 * <p/>
 * More todo: Quote-Level cannot be resolved, until the content has been
 * processed by the renderer. The Quote-Tokens need to be passed down to the
 * renderer unchanged; they need the defined quotes for the current element when
 * being printed.
 * <p/>
 * The language is currently unresolved. It needs to be takes from the parent
 * context or the xml:lang attribute. Resolving the language using stylesheets
 * does not work, as there is a language-matching rule which depends on that
 * value.
 * <p/>
 * Todo: DisplayNone does not remove the element from the document tree. Quote:
 * <p/>
 * The element is not rendered. The rendering is the same as if the element had
 * been removed from the document tree, except for possible effects on counters
 * (see [generated] or [paged]).
 * <p/>
 * [generated]: An element that is not displayed ('display' set to 'none')
 * cannot increment or reset a counter.
 * <p/>
 * Note that :before and :after pseudo elements of this element are also not
 * rendered, see [generated].)
 *
 * @author Thomas Morgner
 */
public class ContentNormalizer implements Normalizer
{
  protected static class ContentNormalizerState implements State
  {
    private State modelBuilderState;

    // The LayoutElements are immutable; only their LayoutContext may change
    private LayoutElement currentElement;
    private LayoutElement currentSilbling;

    private long nextId;
    private State recordingContentNormalizerState;

    protected ContentNormalizerState()
    {
    }

    public State getRecordingContentNormalizerState()
    {
      return recordingContentNormalizerState;
    }

    public void setRecordingContentNormalizerState(final State recordingContentNormalizerState)
    {
      this.recordingContentNormalizerState = recordingContentNormalizerState;
    }

    public State getModelBuilderState()
    {
      return modelBuilderState;
    }

    public void setModelBuilderState(final State modelBuilderState)
    {
      this.modelBuilderState = modelBuilderState;
    }

    public LayoutElement getCurrentElement()
    {
      return currentElement;
    }

    public void setCurrentElement(final LayoutElement currentElement)
    {
      this.currentElement = currentElement;
    }

    public LayoutElement getCurrentSilbling()
    {
      return currentSilbling;
    }

    public void setCurrentSilbling(final LayoutElement currentSilbling)
    {
      this.currentSilbling = currentSilbling;
    }

    public long getNextId()
    {
      return nextId;
    }

    public void setNextId(final long nextId)
    {
      this.nextId = nextId;
    }

    /**
     * Creates a restored instance of the saved component.
     * <p/>
     * By using this factory-like approach, we gain independence from having to
     * know the actual implementation. This makes things a lot easier.
     *
     * @param layoutProcess the layout process that controls it all
     * @return the saved state
     * @throws StateException
     */
    public StatefullComponent restore(final LayoutProcess layoutProcess)
        throws StateException
    {
      final ContentNormalizer contentNormalizer =
          new ContentNormalizer(layoutProcess, false);
      contentNormalizer.restore(this);
      return contentNormalizer;
    }
  }

  private static final long NO_PARENT = -1;


  private ModelBuilder modelBuilder;

  private LayoutElement currentElement;
  private LayoutElement currentSilbling;

  private LayoutProcess layoutProcess;
  private RecordingContentNormalizer recordingContentNormalizer;
  private long nextId;
  private int ignoreContext;

  /**
   * The quote-level is a global setting. The quotes get resolved during the
   * content generation phase.
   */
  private int quoteLevel;
  private StyleResolver styleResolver;


  public ContentNormalizer(final LayoutProcess layoutProcess)
  {
    this(layoutProcess, true);
  }

  protected ContentNormalizer(final LayoutProcess layoutProcess,
                              final boolean init)
  {
    if (layoutProcess == null)
    {
      throw new NullPointerException("LayoutProcess must not be null.");
    }
    this.layoutProcess = layoutProcess;
    this.styleResolver = layoutProcess.getStyleResolver();

    if (init)
    {
      this.modelBuilder = layoutProcess.getOutputProcessor().createModelBuilder
          (layoutProcess);
    }
  }

  public void startDocument()
      throws IOException, NormalizationException
  {
    styleResolver.initialize(layoutProcess);

    final DefaultPageContext dpc = new DefaultPageContext();
    final PageAreaType[] pat = PageAreaType.getPageAreas();
    for (int i = 0; i < pat.length; i++)
    {
      final PageAreaType pageAreaType = pat[i];
      final LayoutStyle style = styleResolver.resolvePageStyle
          (CSSAutoValue.getInstance(), new PseudoPage[0], pageAreaType);
      dpc.setAreaDefinition(pageAreaType, style);
    }
    final LayoutStyle areaDefinition =
        dpc.getAreaDefinition(PageAreaType.CONTENT);


    modelBuilder.startDocument(dpc);
  }

  /**
   * Starts a new element. The element uses the given namespace and tagname. The
   * element's attributes are given as collection, each attribute is keyed with
   * a namespace and attributename. The values contained in the attributes are
   * not defined.
   *
   * @param namespace
   * @param tag
   * @param attributes
   * @throws NormalizationException
   * @throws IOException
   */
  public void startElement(final String namespace,
                           final String tag,
                           final AttributeMap attributes)
      throws NormalizationException, IOException
  {
    // the contents of what is stored here is rather uninteresting,
    // important is the fact *that* we saved something.
    //
    // This is not correct yet, as right now, this would not record a
    // html->head->title if the html->head element is not displayed.
    if (recordingContentNormalizer != null)
    {
      recordingContentNormalizer.startElement(namespace, tag, attributes);
      return;
    }
    startElementInternal(namespace, tag, null, attributes);
  }

  protected void startElementInternal(final String namespace,
                                      final String tag,
                                      final String pseudo,
                                      final AttributeMap attributes)
      throws NormalizationException, IOException
  {

    final ContextId ctxId = new ContextId
        (ContextId.SOURCE_NORMALIZER, NO_PARENT, nextId);
    nextId += 1;

    final LayoutContext layoutContext = new DefaultLayoutContext
        (ctxId, namespace, tag, pseudo, attributes);
    final LayoutElement element =
        new LayoutElement(currentElement, currentSilbling, layoutContext);
    currentElement = element;
    currentSilbling = null;

    styleResolver.resolveStyle(element);
    if (isStringRecordingNeeded(element))
    {
      // this will record all calls. We later go through and extract all
      // CDATA - regardless of the element content. Extracting is done,
      // even if the element has the display:none condition.
      recordingContentNormalizer = new RecordingContentNormalizer();
    }
    else
    {
      startCurrentElement();
    }
  }

  /**
   * Processes the current element. The element has been resolved fully and it
   * is made sure that it can be processed right now (No pinning is enabled).
   *
   * @throws NormalizationException
   * @throws IOException
   */
  private void startCurrentElement()
      throws NormalizationException, IOException
  {
    final LayoutContext layoutContext = currentElement.getLayoutContext();
    final CSSValue displayRole = layoutContext.getValue(BoxStyleKeys.DISPLAY_ROLE);
    if (DisplayRole.NONE.equals(displayRole))
    {
      // ignore that element ..
      ignoreContext += 1;
//      Log.debug("Ignoring element (and all childs) of " +
//          layoutContext.getPseudoElement() +
//          " as it has Display:NONE");
    }
    else if (ignoreContext > 0)
    {
      // keep track of our distance to the first hidden element
      ignoreContext += 1;
    }

//    Log.debug ("Element " + layoutContext.getTagName() + " " + displayRole);

    // update counters and strings ...
    if (DisplayRole.LIST_ITEM.equals(displayRole))
    {
      currentElement.incrementCounter("list-item", 1);
    }

    if (ignoreContext > 0)
    {
      return;
    }

    // check, whether the element allows content at all..
    // isAllowContentProcessing is false, if the 'content' property
    // had been set to 'none' or 'inhibit'.
    final ContentSpecification contentSpec =
        currentElement.getLayoutContext().getContentSpecification();
    if (contentSpec.isAllowContentProcessing() == false)
    {
      // Quote-the-standard:
      // -------------------
      // On elements, this inhibits the children of the element from
      // being rendered as children of this element, as if the element
      // was empty.
      //
      // On pseudo-elements, this inhibits the creation of the pseudo-element,
      // as if 'display' computed to 'none'.
      //
      // In both cases, this further inhibits the creation of any
      // pseudo-elements which have this pseudo-element as a superior.
      if (contentSpec.isInhibitContent() &&
          layoutContext.isPseudoElement())
      {
//          Log.debug("Starting to ignore childs of psuedo element " +
//                  layoutContext.getTagName() + ":" +
//                  layoutContext.getPseudoElement() +
//                  " as it inhibits content creation.");
        modelBuilder.startElement(currentElement.detachLayoutContext());
        ignoreContext += 1;
        return;
      }
//          Log.debug("Starting to ignore childs of element " +
//                  layoutContext.getTagName() +
//                  " as it inhibits content creation.");
      generateOutsidePseudoElements(currentElement);
      modelBuilder.startElement(currentElement.detachLayoutContext());
      generateBeforePseudoElements(currentElement);
      generateContentBefore(currentElement);
      ignoreContext += 1;
      return;
    }

    // normal content processing here ...
    generateOutsidePseudoElements(currentElement);
    modelBuilder.startElement(currentElement.detachLayoutContext());
    generateBeforePseudoElements(currentElement);

    // check, whether we have a 'contents' token inside the 'content'
    // style property.
    generateContentBefore(currentElement);
    if (currentElement.isContentsConsumed() == false)
    {
      // we have none, so we will ignore all other content of that element
      // lets generate an 'alternate-element'
      if (generateAlternateContent(currentElement) == false)
      {
//            Log.debug("Starting to ignore childs of element " + currentElement +
//                    " as it does not contain the 'contents' token.");
        ignoreContext += 1;
      }
    }
  }

  protected boolean generateBeforePseudoElements(final LayoutElement element)
      throws IOException, NormalizationException
  {
    final LayoutContext layoutContext = element.getLayoutContext();

    final CSSValue displayRole = layoutContext.getValue(BoxStyleKeys.DISPLAY_ROLE);
    if (DisplayRole.LIST_ITEM.equals(displayRole))
    {
      if (styleResolver.isPseudoElementStyleResolvable(element, "marker"))
      {
        startElementInternal(layoutContext.getNamespace(),
            layoutContext.getTagName(), "marker",
            layoutContext.getAttributes());
        endElement();
      }
    }

    // it might be against the standard, but we do not accept the
    // contents-token here.
    if (styleResolver.isPseudoElementStyleResolvable(element, "before"))
    {
      startElementInternal(layoutContext.getNamespace(),
          layoutContext.getTagName(), "before",
          layoutContext.getAttributes());
      endElement();
    }

    return false;
  }

  /**
   * Return true, if the alternate element contained the contents token. In that
   * case, this element receives all content. We have to make sure that the
   * beast gets closed down later ..
   *
   * @param element
   * @return true, if the contents token has been encountered, false otherwise.
   */
  private boolean generateAlternateContent(final LayoutElement element)
      throws IOException, NormalizationException
  {
    // it might be against the standard, but we do not accept the
    // contents-token here.
    if (element.isContentsConsumed())
    {
      return false;
    }
    // we do not generate an alternate element, if there is no need to do so.
    if (styleResolver.isPseudoElementStyleResolvable(element, "alternate"))
    {
      final LayoutContext layoutContext = element.getLayoutContext();
      startElementInternal(layoutContext.getNamespace(),
          layoutContext.getTagName(), "alternate",
          layoutContext.getAttributes());
      if (element.isContentsConsumed())
      {
        // if the alternate element consumes the content, fine. We have
        // to close the element later ..
        element.openAlternate();
        return true;
      }
      endElement();
    }
    return false;
  }

  private boolean generateOutsidePseudoElements(final LayoutElement element)
      throws IOException, NormalizationException
  {
    final LayoutContext layoutContext = element.getLayoutContext();

    final CSSValue value = layoutContext.getValue(ContentStyleKeys.MOVE_TO);
    if (MoveToValues.HERE.equals(value) == false)
    {
      // Some moved content.
      final String target;
      if (value == null)
      {
        target = null;
      }
      else if (value instanceof CSSStringValue)
      {
        final CSSStringValue sval = (CSSStringValue) value;
        target = sval.getValue();
      }
      else
      {
        target = value.getCSSText();
      }

      layoutContext.getContentSpecification().setMoveTarget(target);

      // we do not generate an alternate element, if there is no need to do so.
      if (styleResolver.isPseudoElementStyleResolvable(element, "alternate"))
      {
        startElementInternal(layoutContext.getNamespace(),
            layoutContext.getTagName(), "alternate",
            layoutContext.getAttributes());
        if (element.isContentsConsumed())
        {
          // if the alternate element consumes the content, fine. We have
          // to close the element later ..
          element.openAlternate();
        }
        else
        {
          endElement();
        }
      }
    }

    return false;
  }

  /**
   * There are two cases, when elements need recording. First, if there is a
   * 'string-set' property with a 'contents()' token. We have to copy all
   * char-data content from the element. The content will be availble *after*
   * the element has been closed. It will not be available while the element is
   * processed. All content processing is suspended until the whole char-data
   * has been extracted. Generated content is not extracted at all - we work on
   * the user's data only.
   * <p/>
   * The recorded content is replayed when the element ends (as signaled by the
   * input-feed) so that the string-content WILL be available for all childs.
   * Warning: This possibly duplicates content and is definitly an expensive
   * operation.
   */
  private boolean isStringRecordingNeeded(final LayoutElement element)
  {
    final ContentSpecification contentSpecification =
        element.getLayoutContext().getContentSpecification();
    final ContentToken[] strings = contentSpecification.getStrings();

    // todo: This might be invalid.

    final LayoutContext layoutContext = element.getLayoutContext();
    final CSSValue value = layoutContext.getValue(ContentStyleKeys.STRING_DEFINE);
    if (value == null)
    {
      return false;
    }
    if (value instanceof CSSValueList)
    {
      final CSSValueList list = (CSSValueList) value;
      if (list.getLength() == 0)
      {
        return false;
      }
      for (int i = 0; i < list.getLength(); i++)
      {
        final CSSValue val = list.getItem(i);
        if (val instanceof ContentsToken)
        {
          return true;
        }
      }
    }
    return false;
  }

  protected boolean generateContentBefore(final LayoutElement element)
      throws IOException, NormalizationException
  {
    final ContentSpecification cspec =
        element.getLayoutContext().getContentSpecification();
    final ContentToken[] tokens = cspec.getContents();
    for (int i = 0; i < tokens.length; i++)
    {
      final ContentToken token = tokens[i];
      if (token instanceof ContentsToken)
      {
        element.setContentsConsumed(true);
        return true;
      }
      if (token instanceof ComputedToken)
      {
        final ContentToken resolved = computeToken(token, cspec);
        if (resolved != null)
        {
          addContent(resolved);
        }
      }
      else
      {
        addContent(token);
      }
    }
    return false;
  }

  protected void generateContentAfter(final LayoutElement element)
      throws IOException, NormalizationException
  {
    final ContentSpecification cspec =
        element.getLayoutContext().getContentSpecification();
    final ContentToken[] tokens = cspec.getContents();
    int posContent = 0;
    // first skip everything up to the first 'contents' token.
    for (; posContent < tokens.length; posContent++)
    {
      final ContentToken token = tokens[posContent];
      if (token instanceof ContentsToken)
      {
        break;
      }
    }
    posContent += 1;
    for (; posContent < tokens.length; posContent++)
    {
      final ContentToken token = tokens[posContent];
      // subsequent contents tokens are ignored ..
      if (token instanceof ContentsToken)
      {
        continue;
      }

      if (token instanceof ComputedToken)
      {
        final ContentToken resolved = computeToken(token, cspec);
        if (resolved != null)
        {
          addContent(resolved);
        }
      }
      else
      {
        addContent(token);
      }
    }
  }


  protected void generateStrings(final LayoutElement element)
      throws IOException, NormalizationException
  {
    final ContentSpecification cspec =
        element.getLayoutContext().getContentSpecification();
    final ContentToken[] tokens = cspec.getContents();
    int posContent = 0;
    boolean contentGiven = false;
    // first skip everything up to the first 'contents' token.
    for (; posContent < tokens.length; posContent++)
    {
      final ContentToken token = tokens[posContent];
      if (token instanceof ContentsToken)
      {
        if (contentGiven == false)
        {
          // content is given more than once, then ignore it
          final String text = recordingContentNormalizer.getText();
          addContent(new ResolvedStringToken((ComputedToken) token, text));
          contentGiven = true;
        }
      }
      else if (token instanceof ComputedToken)
      {
        final ContentToken resolved = computeToken(token, cspec);
        if (resolved != null)
        {
          addContent(resolved);
        }
      }
      else
      {
        addContent(token);
      }
    }
  }


  protected void generateAfterPseudoElements(final LayoutElement element)
      throws IOException, NormalizationException
  {
    final LayoutContext layoutContext = element.getLayoutContext();
    // it might be against the standard, but we do not accept the
    // contents-token here.
    if (styleResolver.isPseudoElementStyleResolvable(element, "after"))
    {
      startElementInternal(layoutContext.getNamespace(),
          layoutContext.getTagName(), "after",
          layoutContext.getAttributes());
      endElement();
    }

  }

  /**
   * Adds text content to the current element.
   *
   * @param text
   * @throws NormalizationException
   * @throws IOException
   */
  public void addText(final String text) throws NormalizationException, IOException
  {
    if (ignoreContext > 0)
    {
      // Log.debug ("Ignored context active: " + ignoreContext);
      if (recordingContentNormalizer != null)
      {
        recordingContentNormalizer.addText(text);
      }
      return;
    }

    //Log.debug ("Adding: " + text);
    modelBuilder.addContent(new StaticTextToken(text));
  }

  private void addContent(final ContentToken token)
      throws NormalizationException
  {
    if (token instanceof ComputedToken)
    {
      throw new NormalizationException("ComputedContent cannot be added.");
    }
    if (ignoreContext == 0)
    {
      modelBuilder.addContent(token);
    }
  }

  private ContentToken computeToken(final ContentToken token,
                                    final ContentSpecification contentSpecs)
  {
    if (token instanceof CloseQuoteToken)
    {
      final CloseQuoteToken closeQuoteToken = (CloseQuoteToken) token;
      if (closeQuoteToken.isSurpressQuoteText())
      {
        quoteLevel -= 1;
        return null;
      }
      // Important: The quote level must be decreased before the quote gets
      // queried. (To be in sync with the open-quote thing..
      quoteLevel -= 1;
      final QuotesPair currentQuote = getQuotesPair();
      if (currentQuote != null)
      {
        return new ResolvedStringToken
            (closeQuoteToken, currentQuote.getCloseQuote());
      }
    }
    else if (token instanceof OpenQuoteToken)
    {
      final OpenQuoteToken openQuoteToken = (OpenQuoteToken) token;
      if (openQuoteToken.isSurpressQuoteText())
      {
        quoteLevel += 1;
        return null;
      }

      // Important: The quote level must be increased after the quote has
      // been queried. Our quoting implementation uses zero-based arrays.
      final QuotesPair currentQuote = getQuotesPair();
      quoteLevel += 1;
      if (currentQuote != null)
      {
        return new ResolvedStringToken
            (openQuoteToken, currentQuote.getOpenQuote());
      }
    }
    else if (token instanceof VariableToken)
    {
      final VariableToken variableToken = (VariableToken) token;
      final String resolvedText =
          currentElement.getString(variableToken.getVariable());
      return new ResolvedStringToken(variableToken, resolvedText);
    }
    else if (token instanceof CounterToken)
    {
      final CounterToken counterToken = (CounterToken) token;
      final String name = counterToken.getName();
      final int counterValue = currentElement.getCounterValue(name);
      return new ResolvedCounterToken(counterToken, counterValue);
    }
    else if (token instanceof CountersToken)
    {
      final CountersToken counterToken = (CountersToken) token;
      final String name = counterToken.getName();
      final IntList counterValues = new IntList(10);
      while (currentElement != null)
      {
        if (currentElement.isCounterDefined(name))
        {
          counterValues.add(currentElement.getCounterValue(name));
        }
        currentElement = currentElement.getParent();
      }

      final int counterCount = counterValues.size();
      final int[] ints = new int[counterCount];
      for (int i = 0; i < counterCount; i++)
      {
        ints[i] = counterValues.get(counterCount - i - 1);
      }
      return new ResolvedCountersToken(counterToken, ints);
    }
    // not recognized ...
    return null;
  }

  private QuotesPair getQuotesPair()
  {
    final ContentSpecification cspec =
        currentElement.getLayoutContext().getContentSpecification();
    final QuotesPair[] qps = cspec.getQuotes();
    final int maxQuote = Math.min(qps.length - 1, quoteLevel);
    if (maxQuote == -1)
    {
      return null;
    }
    else
    {
      return qps[maxQuote];
    }
  }

  /**
   * Ends the current element. The namespace and tagname are given for
   * convienience.
   *
   * @throws NormalizationException
   * @throws IOException
   */
  public void endElement()
      throws NormalizationException, IOException
  {

//    final LayoutElement element = currentElement;
    if (currentElement == null)
    {
      throw new NullPointerException
          ("This is unexpected: I dont have a current element.");
    }

    if (ignoreContext > 1)
    {
      // this is an inner ignored element.
      ignoreContext -= 1;
      if (recordingContentNormalizer != null)
      {
        recordingContentNormalizer.endElement();
      }
      currentSilbling = currentElement;
      currentElement = currentElement.getParent();
      return;
    }

    if (ignoreContext == 1)
    {
      // check, what caused the trouble ..
      final LayoutContext layoutContext = currentElement.getLayoutContext();
      final CSSValue displayRole = layoutContext.getValue(BoxStyleKeys.DISPLAY_ROLE);
      if (DisplayRole.NONE.equals(displayRole))
      {
        // ok, no need to clean up.
        currentSilbling = currentElement;
        currentElement = currentElement.getParent();
        ignoreContext = 0;
        recordingContentNormalizer = null;
        return;
      }
    }

    if (currentElement.isAlternateOpen())
    {
      endElement();
    }

    if (ignoreContext == 1)
    {
      final LayoutContext layoutContext = currentElement.getLayoutContext();
      final ContentSpecification contentSpec =
          layoutContext.getContentSpecification();

      // replace the contents token of the string-keystyle with the
      // extracted content.
      generateStrings(currentElement);
      if (contentSpec.isAllowContentProcessing() == false)
      {
        if (!contentSpec.isInhibitContent() ||
            !layoutContext.isPseudoElement())
        {
          // clean up (2): The element generated some stuff..
          generateAfterPseudoElements(currentElement);
        }
      }
      else
      {
        generateContentAfter(currentElement);
        // clean up (2): The element generated some stuff..
        generateAfterPseudoElements(currentElement);
        // clean up (1): Just finish the element
      }

      ignoreContext = 0;
      if (recordingContentNormalizer != null)
      {
        try
        {
          recordingContentNormalizer.replay(this);
          recordingContentNormalizer = null;
        }
        catch (ChainingCallException e)
        {
          // Now reiterate over all the stored content so that the normal
          // content flow is preserved.
        }
      }
    }
    else
    {
      generateContentAfter(currentElement);
      generateAfterPseudoElements(currentElement);
    }

    modelBuilder.endElement();

    if (currentElement.isAlternateOpen())
    {
      endElement();
    }

    currentSilbling = currentElement;
    currentElement = currentElement.getParent();
  }

  public void endDocument()
      throws IOException, NormalizationException
  {
    modelBuilder.endDocument();
  }

  public void handlePageBreak(final CSSValue pageName,
                              final PseudoPage[] pseudoPages)
  {

    final DefaultPageContext dpc = new DefaultPageContext();
    final PageAreaType[] pat = PageAreaType.getPageAreas();
    for (int i = 0; i < pat.length; i++)
    {
      final PageAreaType pageAreaType = pat[i];
      if (styleResolver == null)
      {
        throw new IllegalStateException();
      }

      final LayoutStyle style = styleResolver.resolvePageStyle
          (pageName, pseudoPages, pageAreaType);
      dpc.setAreaDefinition(pageAreaType, style);
    }
    try
    {
      modelBuilder.handlePageBreak(dpc);
    }
    catch (NormalizationException e)
    {
      // this is a bit unclean ..
      throw new IllegalStateException();
    }
  }

  protected ContentNormalizerState createSaveState()
  {
    return new ContentNormalizerState();
  }

  protected void fillState(final ContentNormalizerState state) throws StateException
  {
    state.setNextId(nextId);
    state.setCurrentElement(currentElement);
    state.setCurrentSilbling(currentSilbling);
    state.setModelBuilderState(modelBuilder.saveState());
    if (recordingContentNormalizer != null)
    {
      state.setRecordingContentNormalizerState(
          recordingContentNormalizer.saveState());
    }
  }

  public State saveState() throws StateException
  {
    final ContentNormalizerState state = createSaveState();
    fillState(state);
    return state;
  }

  protected void restore(final ContentNormalizerState state)
      throws StateException
  {
    this.currentElement = state.getCurrentElement();
    this.currentSilbling = state.getCurrentSilbling();
    this.nextId = state.getNextId();
    this.modelBuilder = (ModelBuilder)
        state.getModelBuilderState().restore(layoutProcess);
    if (state.getRecordingContentNormalizerState() != null)
    {
      this.recordingContentNormalizer = (RecordingContentNormalizer)
          state.getRecordingContentNormalizerState().restore(layoutProcess);
    }
  }

  /**
   * Returns the renderer. The renderer is the last step in the processing
   * chain. The ModelBuilder and ContentGenerator steps are considered internal,
   * as they may refeed the normalizer.
   *
   * @return the current renderer
   */
  public Renderer getRenderer()
  {
    return modelBuilder.getRenderer();
  }

  public StyleResolver getStyleResolver()
  {
    if (styleResolver == null)
    {
      throw new IllegalStateException("Document has not yet been initialized?");
    }
    return styleResolver;
  }
}