01 /**
02  * An object for iterating a {@link TypedSource} object by getting connected pieces of Java source
03  * code having the same type. Line breaks are omitted, but empty lines will be covered.
04  
05  @see SourceRun
06  */
07 
08 package de.java2html.javasource;
09 
10 import java.util.Iterator;
11 import java.util.NoSuchElementException;
12 
13 public class TypedSourceIterator implements Iterator<SourceRun> {
14 
15   private final TypedSource javaSource;
16   private int startIndex;
17   private int endIndex;
18   private boolean finished;
19   private boolean isNewLine;
20 
21   public TypedSourceIterator(TypedSource javaSource) {
22     this.javaSource = javaSource;
23     finished = false;
24     isNewLine = false;
25     startIndex = 0;
26     endIndex = 0;
27     if (javaSource.getCode().length() == 0) {
28       finished = true;
29     }
30   }
31 
32   private void seekToNext() {
33     if (isNewLine) {
34       startIndex = endIndex + 2;
35       endIndex = startIndex + 1;
36       isNewLine = false;
37     }
38     else {
39       startIndex = endIndex;
40       endIndex = startIndex + 1;
41     }
42 
43     if (endIndex > javaSource.getCode().length()) {
44       --endIndex;
45     }
46     while (true) {
47       if (endIndex == javaSource.getCode().length()) {
48         break;
49       }
50       if (endIndex <= javaSource.getCode().length() && javaSource.getCode().charAt(endIndex== '\n') {
51         --endIndex;
52 
53         isNewLine = true;
54         break;
55       }
56       if (javaSource.getClassification()[endIndex!= javaSource.getClassification()[startIndex]
57           && javaSource.getClassification()[endIndex!= SourceType.BACKGROUND) {
58         break;
59       }
60       ++endIndex;
61     }
62   }
63 
64   public boolean hasNext() {
65     return !finished;
66   }
67 
68   public SourceRun getNext() throws NoSuchElementException {
69     if (finished) {
70       throw new NoSuchElementException();
71     }
72     seekToNext();
73 
74     //Sonderfall: Hinter abschliessendem Newline in letzer Zeile ("\r\n")
75     if (startIndex >= javaSource.getCode().length()) {
76       --startIndex;
77       --endIndex;
78     }
79     final SourceRun run = new SourceRun(javaSource, startIndex, endIndex);
80     finished = endIndex == javaSource.getCode().length();
81     return run;
82   }
83 
84   public SourceRun next() throws NoSuchElementException {
85     return getNext();
86   }
87 
88   public void remove() {
89     //nothing to do
90   }
91 }