Add predefined Velocity and CSS template if wiki builder is assigned to a project
[phpeclipse.git] / archive / net.sourceforge.phpeclipse.wiki / src / net / sourceforge / phpeclipse / wiki / renderer / AbstractContentRenderer.java
1 package net.sourceforge.phpeclipse.wiki.renderer;
2
3 import java.io.IOException;
4
5 import net.sourceforge.phpeclipse.wiki.editor.WikiEditor;
6 import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin;
7
8 import org.eclipse.core.resources.IProject;
9 import org.eclipse.jface.text.BadLocationException;
10 import org.eclipse.jface.text.IDocument;
11
12 public abstract class AbstractContentRenderer implements IContentRenderer {
13   protected IProject fProject;
14
15   public static final String CLASS_MONO_SPACE = "monospace";
16
17   public static final String CLASS_QUOTE = "quote";
18
19   public static final String TABLE_DELIMETER = "|";
20
21   public static final String HR = "hr";
22
23   public static final String NEW_WIKIDOC_HREF = "?";
24
25   public static final String WIKI_HREF = "http://--wiki/";
26
27   public static final String[][] REPLACE_TEXT = new String[][] { { "<", "&lt;" }, { "\"", "&quot;" } };
28
29   private WikiEditor editor;
30
31   protected StringBuffer buffer;
32
33   private int currentLine;
34
35   private int currentListDepth;
36
37   private boolean inTable;
38
39   private void setEditor(WikiEditor editor) {
40     this.editor = editor;
41   }
42
43   protected StringBuffer getBuffer() {
44     return buffer;
45   }
46
47   protected WikiEditor getEditor() {
48     return editor;
49   }
50
51   //  public void render(String content, StringBuffer buf) {
52   //    try {
53   //      buffer = buf;
54   //      appendHeader();
55   //
56   //      int index = 0;
57   //      int startIndex = 0;
58   //      String line;
59   //      while (index < content.length()) {
60   //        if (content.charAt(index++) == '\n') {
61   //          line = content.substring(startIndex, index);
62   //          startIndex = index;
63   //          appendLine(line);
64   //
65   //        }
66   //        index++;
67   //      }
68   //      if (startIndex < content.length()) {
69   //        line = content.substring(startIndex, content.length());
70   //        renderLine(line);
71   //      }
72   //      appendFooter();
73   //      // return buffer.toString();
74   //    } catch (Exception e) {
75   //      WikiEditorPlugin.getDefault().log(buffer.toString());
76   //      WikiEditorPlugin.getDefault().log(e.getLocalizedMessage(), e);
77   //      // return "<html><body><p>" + e.getLocalizedMessage() +
78   //      // "</p></body></html>";
79   //    }
80   //  }
81
82   //  protected void renderLine(String line) {
83   //    if (isHeader(line)) {
84   //      appendHeader(line);
85   //    } else if (isList(line)) {
86   //      appendListItem(line);
87   //    } else if (tableLine(line)) {
88   //      processTable(line);
89   //    } else if (process(line)) {
90   //      return;
91   //    } else {
92   //      buffer.append(line);
93   //    }
94   //  }
95
96   //  public final String render(WikiEditor editor) {
97   //    initialise(editor);
98   //    try {
99   //      buffer = new StringBuffer();
100   //      appendHeader();
101   //      buffer.append("<h1>").append(editor.getWikiNameBeingEdited()).append("</h1>");
102   //      appendContents();
103   //      appendFooter();
104   //      return buffer.toString();
105   //    } catch (Exception e) {
106   //      WikiEditorPlugin.getDefault().log(buffer.toString());
107   //      WikiEditorPlugin.getDefault().log(e.getLocalizedMessage(), e);
108   //      return "<html><body><p>" + e.getLocalizedMessage() + "</p></body></html>";
109   //    }
110   //  }
111
112   private void initialise(WikiEditor editor) {
113     setEditor(editor);
114     currentListDepth = 0;
115     inTable = false;
116     initialise();
117   }
118
119   protected abstract void initialise();
120
121   protected void appendHeader(StringBuffer buf) throws IOException {
122     buf.append("<html><head>");
123     //    String basePath = Util.getMiscProjectsPreferenceValue(fProject, WikiConstants.HTML_OUTPUT_PATH);
124     //    buffer.append("<base href=\"" + basePath + "/" + fProject.getName() + "\"/>");
125
126     //    if (WikiEditorPlugin.getDefault().getPluginPreferences().contains(WikiConstants.BROWSER_CSS_URL)) {
127     //      buffer.append("<link href=\"")
128     //          .append(WikiEditorPlugin.getDefault().getPluginPreferences().getString(WikiConstants.BROWSER_CSS_URL)).append(
129     //              "\" fType=\"text/css\" rel=\"STYLESHEET\">");
130     //    }
131     //    appendStyle();
132
133     buf.append("</head><body>\n");
134   }
135
136   private void appendContents() {
137     IDocument document = editor.getDocument();
138     currentLine = 0;
139     while (currentLine < document.getNumberOfLines()) {
140       String line = getLine(document, currentLine);
141       //      appendLine(line);
142       currentLine++;
143     }
144   }
145
146   protected void appendNewLine() {
147     getBuffer().append(System.getProperty("line.separator"));
148   }
149
150   //  protected String getNextLine() {
151   //    if (hasLine(currentLine + 1)) {
152   //      currentLine++;
153   //      return getLine(editor.getDocument(), currentLine);
154   //    }
155   //    throw new RuntimeException("Should not be called if there is no next line.");
156   //  }
157
158   //  protected String peekNextLine() {
159   //    if (hasLine(currentLine + 1)) {
160   //      return getLine(editor.getDocument(), currentLine + 1);
161   //    }
162   //    return "";
163   //  }
164
165   protected boolean hasNextLine() {
166     return hasLine(currentLine + 1);
167   }
168
169   private boolean hasLine(int lineNumber) {
170     return lineNumber < editor.getDocument().getNumberOfLines();
171   }
172
173   protected void appendFooter(StringBuffer buf) {
174     buf.append("\n</body></html>");
175   }
176
177   //  protected void appendStyle() throws IOException {
178   //    buffer.append("<style fType=\"text/css\"><!--");
179   //    IPath path = new Path("style").append(RendererFactory.getContentRendererName() + ".css");
180   //    buffer.append(WikiEditorPlugin.getDefault().loadTextContents(path));
181   //    buffer.append("--></style>");
182   //  }
183   //
184   //  protected void appendLine(String line) {
185   //    if (isHeader(line)) {
186   //      appendHeader(line);
187   //    } else if (isList(line)) {
188   //      appendListItem(line);
189   //    } else if (tableLine(line)) {
190   //      processTable(line);
191   //    } else if (process(line)) {
192   //      return;
193   //    } else {
194   //      buffer.append("<p>");
195   //      append(processTags(line));
196   //      buffer.append("</p>");
197   //    }
198   //  }
199
200   //  private final void appendListItem(String line) {
201   //    int bullet = getListDepth(line);
202   //    if (bullet > currentListDepth) {
203   //      repeatAppend("<ul>", bullet - currentListDepth);
204   //      currentListDepth = bullet;
205   //    } else if (bullet < currentListDepth) {
206   //      repeatAppend("</ul>", currentListDepth - bullet);
207   //      currentListDepth = bullet;
208   //    }
209   //    getBuffer().append("<li>");
210   //    String content = "";
211   //    if (bullet < line.length() - 1) {
212   //      content = getListtext(line);
213   //    }
214   //    append(processTags(content));
215   //    getBuffer().append("</li>");
216   //    if (!isList(peekNextLine())) {
217   //      repeatAppend("</ul>", currentListDepth);
218   //      currentListDepth = 0;
219   //    }
220   //  }
221
222   protected abstract String getListtext(String line);
223
224   protected void repeatAppend(String item, int n) {
225     for (int i = 0; i < n; i++) {
226       getBuffer().append(item);
227     }
228   }
229
230   protected abstract int getListDepth(String line);
231
232   protected abstract String processTags(String line);
233
234   private String getLine(IDocument document, int n) {
235     try {
236       String line = document.get(document.getLineOffset(n), document.getLineLength(n));
237       if (document.getLineDelimiter(n) != null) {
238         line = line.substring(0, line.length() - document.getLineDelimiter(n).length());
239       }
240       for (int i = 0; i < REPLACE_TEXT.length; i++) {
241         line = line.replaceAll(REPLACE_TEXT[i][0], REPLACE_TEXT[i][1]);
242       }
243       return line;
244     } catch (BadLocationException e) {
245       WikiEditorPlugin.getDefault().logAndReport("Error", e.getLocalizedMessage(), e);
246       return e.getLocalizedMessage();
247     }
248   }
249
250   //  protected void append(String line) {
251   //    TextRegion[] regions = TextRegionBuilder.getTextRegions(line, editor);
252   //    for (int i = 0; i < regions.length; i++) {
253   //      regions[i].accept(new TextRegionVisitor() {
254   //        public Object visit(UndefinedTextRegion undefinedTextRegion) {
255   //          buffer.append(undefinedTextRegion.getText());
256   //          return null;
257   //        }
258   //
259   //        public Object visit(UrlTextRegion urlTextRegion) {
260   //          appendLink(urlTextRegion.getText(), urlTextRegion.getText());
261   //          return null;
262   //        }
263   //
264   //        public Object visit(WikiNameTextRegion wikiNameTextRegion) {
265   //          if (editor.hasWikiSibling(wikiNameTextRegion)) {
266   //            appendLink(AbstractContentRenderer.WIKI_HREF + wikiNameTextRegion.getText(), wikiNameTextRegion.getText());
267   //          } else {
268   //            buffer.append(wikiNameTextRegion.getText());
269   //            appendLink(AbstractContentRenderer.WIKI_HREF + wikiNameTextRegion.getText(), AbstractContentRenderer.NEW_WIKIDOC_HREF);
270   //          }
271   //          return null;
272   //        }
273   //
274   //        public Object visit(WikiUrlTextRegion wikiUrlTextRegion) {
275   //          String link;
276   //          if (wikiUrlTextRegion.getLink().startsWith(WikiConstants.ECLIPSE_PREFIX)) {
277   //            link = AbstractContentRenderer.WIKI_HREF + wikiUrlTextRegion.getLink();
278   //          } else {
279   //            link = wikiUrlTextRegion.getLink();
280   //          }
281   //          appendLink(link, wikiUrlTextRegion.getText());
282   //          return null;
283   //        }
284   //
285   //        public Object visit(BasicTextRegion basicTextRegion) {
286   //          buffer.append(basicTextRegion.getText());
287   //          return null;
288   //        }
289   //
290   //        public Object visit(EclipseResourceTextRegion eclipseResourceTextRegion) {
291   //          appendLink(AbstractContentRenderer.WIKI_HREF + eclipseResourceTextRegion.getText(), eclipseResourceTextRegion.getText());
292   //          return null;
293   //        }
294   //
295   //        public Object visit(JavaTypeTextRegion region) {
296   //          try {
297   //            if (region.getType().getUnderlyingResource() != null) {
298   //              String url = AbstractContentRenderer.WIKI_HREF + WikiConstants.ECLIPSE_PREFIX
299   //                  + region.getType().getUnderlyingResource().getFullPath().toString();
300   //              appendLink(url, region.getText());
301   //            } else {
302   //              append(region.getText());
303   //            }
304   //          } catch (JavaModelException e) {
305   //            WikiPlugin.getDefault().logAndReport("Error", e.getLocalizedMessage(), e);
306   //          }
307   //          return null;
308   //        }
309   //
310   //      });
311   //    }
312   //  }
313
314   protected void appendLink(String url, String text) {
315     buffer.append("<a href=\"").append(url).append("\">").append(text).append("</a>");
316   }
317
318   protected abstract boolean isHeader(String line);
319
320 //  protected abstract void appendHeader(String line);
321
322   protected abstract boolean isList(String line);
323
324   /**
325    * Gives implementors a chance to do processing on this line.
326    * 
327    * @return if true, the line will not be processed further
328    */
329   protected abstract boolean process(String line);
330
331   /**
332    * Replace all occurrences of markeup which occurs in pairs with an opening and closing tag in the given line. e.g.
333    * 
334    * <pre>
335    * 
336    *  
337    *   
338    *    
339    *     
340    *          replacePair(&quot;my ''bold'' word&quot;, &quot;''&quot;, &quot;&lt;b&gt;&quot;, &quot;,&lt;/b&gt;&quot;) returns &quot;my &lt;b&gt;bold&lt;/b&gt; word&quot;
341    *      
342    *     
343    *    
344    *   
345    *  
346    * </pre>
347    */
348   protected String replacePair(String line, String search, String openingTag, String closingTag) {
349     StringBuffer buffer = new StringBuffer();
350     String[] foo = line.split(search);
351     for (int i = 0; i < foo.length; i++) {
352       if (i % 2 == 1) {
353         buffer.append(openingTag).append(foo[i]).append(closingTag);
354       } else {
355         buffer.append(foo[i]);
356       }
357     }
358     return buffer.toString();
359   }
360
361   protected void appendHR() {
362     getBuffer().append("<hr>");
363   }
364
365   private boolean tableLine(String line) {
366     return line.startsWith(AbstractContentRenderer.TABLE_DELIMETER);
367   }
368
369   //  private void processTable(String line) {
370   //    if (!inTable) {
371   //      inTable = true;
372   //      getBuffer().append(getTableTag());
373   //    }
374   //    getBuffer().append("<tr>");
375   //    StringTokenizer tokenizer = new StringTokenizer(line, AbstractContentRenderer.TABLE_DELIMETER);
376   //    while (tokenizer.hasMoreTokens()) {
377   //      String cell = tokenizer.nextToken();
378   //      String element = "td";
379   //      if (cell.trim().startsWith("*")) {
380   //        element = "th";
381   //        cell = cell.replaceAll("\\*", "");
382   //      }
383   //      getBuffer().append("<").append(element).append(">");
384   //      append(processTags(cell));
385   //      getBuffer().append("</").append(element).append(">");
386   //    }
387   //    getBuffer().append("</tr>");
388   //    if (!tableLine(peekNextLine())) {
389   //      getBuffer().append("</table>");
390   //      inTable = false;
391   //    }
392   //  }
393
394   /**
395    * @return the tag for table (can be overridden to add style)
396    */
397   protected String getTableTag() {
398     return "<table>";
399   }
400
401 //  public void forEachHeader(IDocument document, StructureClosure closure) throws BadLocationException {
402 //    for (int i = 0; i < document.getNumberOfLines(); i++) {
403 //      String line = getLine(document, i);
404 //      if (isHeader(line)) {
405 //        String header = getHeaderText(line);
406 //        closure.acceptHeader(header, document.getLineOffset(i));
407 //      }
408 //    }
409 //  }
410
411   /**
412    * Get the header from a line with header markup
413    * 
414    * @param line
415    *          guaranteed to be a valid header as defined by b {@link #isHeader(String) isHeader(String)}
416    */
417 //  protected abstract String getHeaderText(String line);
418
419   /**
420    * @param project
421    *          The fProject to set.
422    */
423   public void setProject(IProject project) {
424     fProject = project;
425   }
426 }