01: // Copyright (C) 2003,2004,2005 by Object Mentor, Inc. All rights reserved.
02: // Released under the terms of the GNU General Public License version 2 or later.
03: package fitnesse.wikitext.widgets;
04:
05: import java.util.Iterator;
06: import java.util.regex.Matcher;
07: import java.util.regex.Pattern;
08:
09: public class TableWidget extends ParentWidget {
10: public static final String REGEXP = "^!?(?:\\|[^\r\n]*?\\|[ \\t\\x0B\\f]*"
11: + LineBreakWidget.REGEXP + ")+";
12:
13: private static final Pattern pattern = Pattern
14: .compile("(!?)(\\|[^\r\n]*?)\\|[ \\t\\x0B\\f]*"
15: + LineBreakWidget.REGEXP);
16:
17: public boolean isTestTable;
18:
19: private int columns = 0;
20:
21: public int getColumns() {
22: return columns;
23: }
24:
25: public TableWidget(ParentWidget parent, String text)
26: throws Exception {
27: super (parent);
28: Matcher match = pattern.matcher(text);
29: if (match.find()) {
30: isTestTable = "!".equals(match.group(1));
31: addRows(text);
32: getMaxNumberOfColumns();
33: } else {
34: // throw Exception?
35: }
36: }
37:
38: private void getMaxNumberOfColumns() {
39: for (Iterator i = children.iterator(); i.hasNext();) {
40: TableRowWidget rowWidget = (TableRowWidget) i.next();
41: columns = Math.max(columns, rowWidget.getColumns());
42: }
43: }
44:
45: public String render() throws Exception {
46: StringBuffer html = new StringBuffer(
47: "<table border=\"1\" cellspacing=\"0\" class=\"table-widget\">\n");
48:
49: int colCount = getColumns();
50: html.append("<colgroup>\n");
51: if (colCount == 1) {
52: html.append("<col class=\"col-single\" />\n");
53: } else {
54: for (int i = 1; i < colCount + 1; i++) {
55: html.append("<col class=\"col-" + i + "\" />\n");
56: }
57: }
58: html.append("</colgroup>\n");
59:
60: html.append(childHtml()).append("</table>\n");
61: return html.toString();
62: }
63:
64: private void addRows(String text) throws Exception {
65: Matcher match = pattern.matcher(text);
66: if (match.find()) {
67: new TableRowWidget(this , match.group(2), isTestTable);
68: addRows(text.substring(match.end()));
69: }
70: }
71: }
|