001package org.hl7.fhir.utilities.xhtml;
002
003/*
004  Copyright (c) 2011+, HL7, Inc.
005  All rights reserved.
006  
007  Redistribution and use in source and binary forms, with or without modification, 
008  are permitted provided that the following conditions are met:
009    
010   * Redistributions of source code must retain the above copyright notice, this 
011     list of conditions and the following disclaimer.
012   * Redistributions in binary form must reproduce the above copyright notice, 
013     this list of conditions and the following disclaimer in the documentation 
014     and/or other materials provided with the distribution.
015   * Neither the name of HL7 nor the names of its contributors may be used to 
016     endorse or promote products derived from this software without specific 
017     prior written permission.
018  
019  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
020  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
021  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
022  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
023  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 
024  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
025  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
026  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
027  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
028  POSSIBILITY OF SUCH DAMAGE.
029  
030 */
031
032
033
034/*
035Copyright (c) 2011+, HL7, Inc
036All rights reserved.
037
038Redistribution and use in source and binary forms, with or without modification, 
039are permitted provided that the following conditions are met:
040
041 * Redistributions of source code must retain the above copyright notice, this 
042   list of conditions and the following disclaimer.
043 * Redistributions in binary form must reproduce the above copyright notice, 
044   this list of conditions and the following disclaimer in the documentation 
045   and/or other materials provided with the distribution.
046 * Neither the name of HL7 nor the names of its contributors may be used to 
047   endorse or promote products derived from this software without specific 
048   prior written permission.
049
050THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
051ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
052WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
053IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
054INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 
055NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
056PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
057WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
058ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
059POSSIBILITY OF SUCH DAMAGE.
060
061*/
062
063import java.awt.Color;
064import java.awt.image.BufferedImage;
065import java.io.ByteArrayOutputStream;
066import java.io.File;
067import java.io.FileOutputStream;
068import java.io.IOException;
069import java.io.InputStream;
070import java.io.OutputStream;
071import java.util.ArrayList;
072import java.util.HashMap;
073import java.util.List;
074import java.util.Map;
075import java.util.Set;
076
077import javax.imageio.ImageIO;
078
079import org.apache.commons.codec.binary.Base64;
080import org.apache.commons.io.FileUtils;
081import org.apache.commons.lang3.StringUtils;
082import org.commonmark.node.Node;
083import org.commonmark.parser.Parser;
084import org.commonmark.renderer.html.HtmlRenderer;
085import org.hl7.fhir.exceptions.FHIRException;
086import org.hl7.fhir.utilities.CommaSeparatedStringBuilder;
087import org.hl7.fhir.utilities.TextFile;
088import org.hl7.fhir.utilities.Utilities;
089import org.hl7.fhir.utilities.filesystem.ManagedFileAccess;
090import org.hl7.fhir.utilities.i18n.RenderingI18nContext;
091
092
093public class HierarchicalTableGenerator {
094  public enum TableGenerationMode {
095    XML, XHTML
096  }
097
098  public static final String TEXT_ICON_REFERENCE = "Reference to another Resource";
099  public static final String TEXT_ICON_PRIMITIVE = "Primitive Data Type";
100  public static final String TEXT_ICON_KEY = "JSON Key Value";
101  public static final String TEXT_ICON_DATATYPE = "Data Type";
102  public static final String TEXT_ICON_RESOURCE = "Resource";
103  public static final String TEXT_ICON_ELEMENT = "Element";
104  public static final String TEXT_ICON_OBJECT_BOX = "Object";
105  public static final String TEXT_ICON_REUSE = "Reference to another Element";
106  public static final String TEXT_ICON_EXTENSION = "Extension";
107  public static final String TEXT_ICON_CHOICE = "Choice of Types";
108  public static final String TEXT_ICON_SLICE = "Slice Definition";
109  public static final String TEXT_ICON_SLICE_ITEM = "Slice Item";
110  public static final String TEXT_ICON_FIXED = "Fixed Value";
111  public static final String TEXT_ICON_EXTENSION_SIMPLE = "Simple Extension";
112  public static final String TEXT_ICON_PROFILE = "Profile";
113  public static final String TEXT_ICON_EXTENSION_COMPLEX = "Complex Extension";
114
115  public static final int NEW_REGULAR = 0;
116  public static final int CONTINUE_REGULAR = 1;
117  public static final int NEW_SLICER = 2;
118  public static final int CONTINUE_SLICER = 3;
119  public static final int NEW_SLICE = 4;
120  public static final int CONTINUE_SLICE = 5;
121  private static final String BACKGROUND_ALT_COLOR = "#F7F7F7";
122  public static boolean ACTIVE_TABLES = false;
123
124  public enum TextAlignment {
125    LEFT, CENTER, RIGHT;  
126  }
127  
128  private static Map<String, String> files = new HashMap<String, String>();
129
130  private class Counter {
131    private int count = -1;
132    private void row() {
133      count++;
134    }
135    private boolean isOdd() {
136      return count % 2 == 1;
137    }
138  }
139  public class Piece {
140    private String tag;
141    private String reference;
142    private String text;
143    private String hint;
144    private String style;
145    private String tagImg;
146    private Map<String, String> attributes;
147    private XhtmlNodeList children;
148    
149    public Piece(String tag) {
150      super();
151      this.tag = tag;
152    }
153    
154    public Piece(String reference, String text, String hint) {
155      super();
156      this.reference = reference;
157      this.text = text;
158      this.hint = hint;
159    }
160    public String getReference() {
161      return reference;
162    }
163    public void setReference(String value) {
164      reference = value;
165    }
166    public String getText() {
167      return text;
168    }
169    public String getHint() {
170      return hint;
171    }
172
173    public String getTag() {
174      return tag;
175    }
176
177    public String getStyle() {
178      return style;
179    }
180
181    public void setTag(String tag) {
182      this.tag = tag;
183    }
184
185    public Piece setText(String text) {
186      this.text = text;
187      return this;
188    }
189
190    public void setHint(String hint) {
191      this.hint = hint;
192    }
193
194    public Piece setStyle(String style) {
195      this.style = style;
196      return this;
197    }
198
199    public Piece addStyle(String style) {
200      if (this.style != null)
201        this.style = this.style+"; "+style;
202      else
203        this.style = style;
204      return this;
205    }
206
207    public void addToHint(String text) {
208      if (this.hint == null)
209        this.hint = text;
210      else
211        this.hint += (this.hint.endsWith(".") || this.hint.endsWith("?") ? " " : ". ")+text;
212    }
213    
214    public boolean hasChildren() {
215      return children != null && !children.isEmpty();
216    }
217
218    public XhtmlNodeList getChildren() {
219      if (children == null)
220        children = new XhtmlNodeList();
221      return children;
222    }
223
224    public Piece addHtml(XhtmlNode x) {
225      getChildren().add(x);
226      return this;
227    }
228    
229    public Piece attr(String name, String value) {
230      if (attributes == null) {
231        attributes = new HashMap<>();
232      }
233      attributes.put(name, value);
234      return this;
235    }
236
237    public String getTagImg() {
238      return tagImg;
239    }
240
241    public Piece setTagImg(String tagImg) {
242      this.tagImg = tagImg;
243      return this;
244    }
245    
246  }
247  
248  public class Cell {
249    private List<Piece> pieces = new ArrayList<HierarchicalTableGenerator.Piece>();
250    private String cellStyle;
251    protected int span = 1;
252    private TextAlignment alignment = TextAlignment.LEFT;
253    private String id;
254 
255    public Cell() {
256      
257    }
258    public Cell(String prefix, String reference, String text, String hint, String suffix) {
259      super();
260      if (!Utilities.noString(prefix))
261        pieces.add(new Piece(null, prefix, null));
262      pieces.add(new Piece(reference, text, hint));
263      if (!Utilities.noString(suffix))
264        pieces.add(new Piece(null, suffix, null));
265    }
266    public List<Piece> getPieces() {
267      return pieces;
268    }
269    public Cell addPiece(Piece piece) {
270      pieces.add(piece);
271      return this;
272    }
273
274
275    
276    public Cell addMarkdown(String md) {
277      if (!Utilities.noString(md)) {
278        try {
279          Parser parser = Parser.builder().build();
280          Node document = parser.parse(md);
281          HtmlRenderer renderer = HtmlRenderer.builder().escapeHtml(true).build();
282          String html = renderer.render(document);  
283          pieces.addAll(htmlToParagraphPieces(html, null));
284        } catch (Exception e) {
285          e.printStackTrace();
286        }
287      }
288      return this;
289    }
290    
291    public Cell addMarkdownNoPara(String md) {
292      return addMarkdownNoPara(md, null);
293    }
294    
295    public Cell addMarkdownNoPara(String md, String style) {
296      try {
297        Parser parser = Parser.builder().build();
298        Node document = parser.parse(md);
299        HtmlRenderer renderer = HtmlRenderer.builder().escapeHtml(true).build();
300        String html = renderer.render(document);  
301        pieces.addAll(htmlToParagraphPieces(html, style));
302      } catch (Exception e) {
303        e.printStackTrace();
304      }
305      return this;
306    }
307    
308    private List<Piece> htmlToParagraphPieces(String html, String style)  {
309      List<Piece> myPieces = new ArrayList<Piece>();
310      try {
311        XhtmlNode node = new XhtmlParser().parseFragment("<html>"+html+"</html>");
312        boolean first = true;
313        for (XhtmlNode c : node.getChildNodes()) {
314          if (first) {
315            first = false;
316          } else {
317            myPieces.add(new Piece("br"));
318            myPieces.add(new Piece("br"));            
319          }
320          if (c.getNodeType() == NodeType.Text) {
321            if (!StringUtils.isWhitespace(c.getContent()))
322              addNode(myPieces, c, style);
323          } else if ("p".equals(c.getName())) {
324            for (XhtmlNode g : c.getChildNodes()) {
325              addNode(myPieces, g, style);
326            }
327          } else {
328           Piece x = new Piece(c.getName());
329           x.getChildren().addAll(c.getChildNodes());
330           if (style != null) {
331             x.addStyle(style);
332           }
333           myPieces.add(x);            
334          }
335        }
336//        String[] paragraphs = html.replace("<p>", "").split("<\\/p>|<br  \\/>");
337//        for (int i=0;i<paragraphs.length;i++) {
338//          if (!paragraphs[i].isEmpty()) {
339//            if (i!=0) {
340//              myPieces.add(new Piece("br"));
341//              myPieces.add(new Piece("br"));
342//            }
343//            myPieces.addAll(htmlFormattingToPieces(paragraphs[i]));
344//          }
345//        }
346      } catch (Exception e) {
347        throw new FHIRException("Exception parsing html: "+e.getMessage()+" for "+html, e);
348      }
349
350      return myPieces;
351    }
352    
353    private List<Piece> htmlFormattingToPieces(String html) throws IOException, FHIRException {
354      List<Piece> myPieces = new ArrayList<Piece>();
355      if (html.contains(("<"))) {
356        XhtmlNode node = new XhtmlParser().parseFragment("<p>"+html+"</p>");
357        for (XhtmlNode c : node.getChildNodes()) {
358          addNode(myPieces, c, null);
359        }
360      } else
361        myPieces.add(new Piece(null, html, null));        
362      return myPieces;
363    }
364    
365    private void addNode(List<Piece> list, XhtmlNode c, String style) {
366      if (c.getNodeType() == NodeType.Text)
367        list.add(styleIt(new Piece(null, c.getContent(), null), style));
368      else if (c.getNodeType() == NodeType.Element) {
369        if (c.getName().equals("a")) {
370          list.add(styleIt(new Piece(c.getAttribute("href"), c.allText(), c.getAttribute("title")), style));                    
371        } else if (c.getName().equals("b") || c.getName().equals("em") || c.getName().equals("strong")) {
372          list.add(styleIt(new Piece(null, c.allText(), null).setStyle("font-face: bold"), style));                    
373        } else if (c.getName().equals("code")) {
374          list.add(styleIt(new Piece(null, c.allText(), null).setStyle("padding: 2px 4px; color: #005c00; background-color: #f9f2f4; white-space: nowrap; border-radius: 4px"), style));                    
375        } else if (c.getName().equals("i")) {
376          list.add(styleIt(new Piece(null, c.allText(), null).setStyle("font-style: italic"), style));
377        } else if (c.getName().equals("pre")) {
378          Piece p = styleIt(new Piece(c.getName()).setStyle("white-space: pre; font-family: courier"), style);
379          list.add(p);
380          p.getChildren().addAll(c.getChildNodes());
381        } else if (c.getName().equals("ul") || c.getName().equals("ol")) {
382          Piece p = styleIt(new Piece(c.getName()), style);
383          list.add(p);
384          p.getChildren().addAll(c.getChildNodes());
385        } else if (c.getName().equals("i")) {
386          list.add(styleIt(new Piece(null, c.allText(), null).setStyle("font-style: italic"), style));                    
387        } else if (c.getName().equals("h1")||c.getName().equals("h2")||c.getName().equals("h3")||c.getName().equals("h4")) {
388          Piece p = styleIt(new Piece(c.getName()), style);
389          list.add(p);
390          p.getChildren().addAll(c.getChildNodes());
391        } else if (c.getName().equals("br")) {
392          list.add(styleIt(new Piece(c.getName()), style));
393        } else {
394          throw new Error("Not handled yet: "+c.getName());
395        }
396      } else
397        throw new Error("Unhandled type "+c.getNodeType().toString());
398    }
399    
400    
401    private Piece styleIt(Piece piece, String style) {
402      if (style != null) {
403        piece.addStyle(style);
404      }
405      return piece;
406    }
407    
408    public Cell addStyle(String style) {
409      for (Piece p : pieces)
410        p.addStyle(style);
411      return this;
412    }
413    public void addToHint(String text) {
414      for (Piece p : pieces)
415        p.addToHint(text);            
416    }
417    public Piece addStyledText(String hint, String alt, String fgColor, String bgColor, String link, boolean border) {
418      Piece p = new Piece(link, alt, hint);
419      p.addStyle("padding-left: 3px");
420      p.addStyle("padding-right: 3px");
421      if (border) {
422        p.addStyle("border: 1px grey solid");
423        p.addStyle("font-weight: bold");
424      }
425      if (fgColor != null) {
426        p.addStyle("color: "+fgColor);
427        p.addStyle("background-color: "+bgColor);
428      } else {
429        p.addStyle("color: black");
430        p.addStyle("background-color: "+bgColor != null ? bgColor : "white");       
431      }
432      pieces.add(p);
433      return p;
434    }
435    public Piece addText(String text) {
436      Piece p = new Piece(null, text, null);
437      pieces.add(p);
438      return p;
439    }
440    public String text() {
441      StringBuilder b = new StringBuilder();
442      for (Piece p : pieces)
443        b.append(p.text);
444      return b.toString();
445    }
446    @Override
447    public String toString() {
448      if (span != 1) {
449        return text()+" {"+span+"}";
450      } else {
451        return text();
452      }
453    }
454    public Cell setStyle(String value) {
455      cellStyle = value;
456      return this;
457    }
458    
459    public Cell span(int value) {
460      span = value;
461      return this;
462    }
463    public Cell center() {
464      alignment = TextAlignment.CENTER;
465      return this;
466    }
467    
468    public String getId() {
469      return id;
470    }
471    public void setId(String id) {
472      this.id = id;
473    }
474
475  }
476
477  public class Title extends Cell {
478    private int width;
479
480    public Title(String prefix, String reference, String text, String hint, String suffix, int width) {
481      super(prefix, reference, text, hint, suffix);
482      this.width = width;
483    }
484
485    public Title(String prefix, String reference, String text, String hint, String suffix, int width, int span) {
486      super(prefix, reference, text, hint, suffix);
487      this.width = width;
488      this.span = span;
489    }
490
491    public Title setStyle(String value) {
492      super.setStyle(value);
493      return this;
494    }
495  }
496  
497  public class Row {
498    private List<Row> subRows = new ArrayList<HierarchicalTableGenerator.Row>();
499    private List<Cell> cells = new ArrayList<HierarchicalTableGenerator.Cell>();
500    private String icon;
501    private String anchor;
502    private String hint;
503    private String color;
504    private int lineColor;
505    private String id;
506    private String opacity;
507    
508    public List<Row> getSubRows() {
509      return subRows;
510    }
511    public List<Cell> getCells() {
512      return cells;
513    }
514    public String getIcon() {
515      return icon;
516    }
517    public void setIcon(String icon, String hint) {
518      this.icon = icon;
519      this.hint = hint;
520    }
521    public String getAnchor() {
522      return anchor;
523    }
524    public void setAnchor(String anchor) {
525      this.anchor = anchor;
526    }
527    public String getHint() {
528      return hint;
529    }
530    public String getColor() {
531      return color;
532    }
533    public void setColor(String color) {
534      this.color = color;
535    }
536    public int getLineColor() {
537      return lineColor;
538    }
539    public void setLineColor(int lineColor) {
540      assert lineColor >= 0;
541      assert lineColor <= 2;
542      this.lineColor = lineColor;
543    }
544    public String getId() {
545      return id;
546    }
547    public void setId(String id) {
548      this.id = id;
549    }
550    public String getOpacity() {
551      return opacity;
552    }
553    public void setOpacity(String opacity) {
554      this.opacity = opacity;
555    }
556    public String text() {
557      CommaSeparatedStringBuilder b = new CommaSeparatedStringBuilder();
558      for (Cell c : cells) {
559        b.append(c.text());
560      }
561      return b.toString();
562    }
563  }
564
565  public class TableModel {
566    private String id;
567    private boolean active;
568    private List<Title> titles = new ArrayList<HierarchicalTableGenerator.Title>();
569    private List<Row> rows = new ArrayList<HierarchicalTableGenerator.Row>();
570    private String docoRef;
571    private String docoImg;
572    private boolean alternating;
573        
574    public TableModel(String id, boolean active) {
575      super();
576      this.id = id;
577      this.active = active;
578    }
579    public List<Title> getTitles() {
580      return titles;
581    }
582    public List<Row> getRows() {
583      return rows;
584    }
585    public String getDocoRef() {
586      return docoRef;
587    }
588    public String getDocoImg() {
589      return docoImg;
590    }
591    public void setDocoRef(String docoRef) {
592      this.docoRef = docoRef;
593    }
594    public void setDocoImg(String docoImg) {
595      this.docoImg = docoImg;
596    }
597    public String getId() {
598      return id;
599    }
600    
601    public void setId(String id) {
602      this.id = id;
603    }
604    public boolean isActive() {
605      return active && ACTIVE_TABLES;
606    }
607    public boolean isAlternating() {
608      return alternating;
609    }
610    public void setAlternating(boolean alternating) {
611      this.alternating = alternating;
612    }
613    
614  }
615
616
617  private String dest;
618  private boolean makeTargets;
619  private String defPath = "";
620
621  /**
622   * There are circumstances where the table has to present in the absence of a stable supporting infrastructure.
623   * and the file paths cannot be guaranteed. For these reasons, you can tell the builder to inline all the graphics
624   * (all the styles are inlined anyway, since the table fbuiler has even less control over the styling
625   *  
626   */
627  private boolean inLineGraphics;  
628  
629  private TableGenerationMode mode;
630  private RenderingI18nContext i18n;
631  private String uniqueLocalPrefix;
632
633  public HierarchicalTableGenerator(RenderingI18nContext i18n) {
634    super();
635    this.i18n = i18n;
636  }
637
638  public HierarchicalTableGenerator(RenderingI18nContext i18n, String uniqueLocalPrefix) {
639    super();
640    this.i18n = i18n;
641    this.uniqueLocalPrefix = uniqueLocalPrefix;
642  }
643
644  public HierarchicalTableGenerator(RenderingI18nContext i18n, String dest, boolean inlineGraphics) {
645    super();
646    this.i18n = i18n;
647    this.dest = dest;
648    this.inLineGraphics = inlineGraphics;
649    this.makeTargets = true;
650    checkSetup();
651  }
652
653  public HierarchicalTableGenerator(RenderingI18nContext i18n, String dest, boolean inlineGraphics, String uniqueLocalPrefix) {
654    super();
655    this.i18n = i18n;
656    this.dest = dest;
657    this.inLineGraphics = inlineGraphics;
658    this.makeTargets = true;
659    this.uniqueLocalPrefix = uniqueLocalPrefix;
660    checkSetup();
661  }
662
663  public HierarchicalTableGenerator(RenderingI18nContext i18n, String dest, boolean inlineGraphics, boolean makeTargets, String defPath, String uniqueLocalPrefix) {
664    super();
665    this.i18n = i18n;
666    this.dest = dest;
667    this.inLineGraphics = inlineGraphics;
668    this.makeTargets = makeTargets;
669    this.defPath = defPath;
670    this.uniqueLocalPrefix = uniqueLocalPrefix;
671    checkSetup();
672  }
673
674  public HierarchicalTableGenerator(RenderingI18nContext i18n, String dest, boolean inlineGraphics, boolean makeTargets, String uniqueLocalPrefix) {
675    super();
676    this.i18n = i18n;
677    this.dest = dest;
678    this.inLineGraphics = inlineGraphics;
679    this.makeTargets = makeTargets;
680    this.uniqueLocalPrefix = uniqueLocalPrefix;
681    checkSetup();
682  }
683
684  public HierarchicalTableGenerator(RenderingI18nContext i18n, String dest, boolean inlineGraphics, boolean makeTargets) {
685    super();
686    this.i18n = i18n;
687    this.dest = dest;
688    this.inLineGraphics = inlineGraphics;
689    this.makeTargets = makeTargets;
690    checkSetup();
691  }
692
693  private void checkSetup() {
694    if (dest == null) {
695      throw new Error("what");
696    }
697  }
698
699  public String getDefPath() {
700    return defPath;
701  }
702
703  public TableModel initNormalTable(String prefix, boolean isLogical, boolean alternating, String id, boolean isActive, TableGenerationMode mode) throws IOException {
704    this.mode = mode;
705    
706    TableModel model = new TableModel(id, isActive);
707    
708    model.setAlternating(alternating);
709    if (mode == TableGenerationMode.XML) {
710      model.setDocoImg(help16AsData());     
711    } else {
712      model.setDocoImg(Utilities.pathURL(prefix, "help16.png"));
713    }
714    model.setDocoRef(Utilities.pathURL("https://build.fhir.org/ig/FHIR/ig-guidance", "readingIgs.html#table-views"));
715    model.getTitles().add(new Title(null, model.getDocoRef(), i18n.formatPhrase(RenderingI18nContext.GENERAL_NAME), i18n.formatPhrase(RenderingI18nContext.GENERAL_LOGICAL_NAME), null, 0));
716    model.getTitles().add(new Title(null, model.getDocoRef(), i18n.formatPhrase(RenderingI18nContext.GENERAL_FLAGS), i18n.formatPhrase(RenderingI18nContext.SD_HEAD_FLAGS_DESC), null, 0));
717    model.getTitles().add(new Title(null, model.getDocoRef(), i18n.formatPhrase(RenderingI18nContext.GENERAL_CARD), i18n.formatPhrase(RenderingI18nContext.SD_HEAD_CARD_DESC), null, 0));
718    model.getTitles().add(new Title(null, model.getDocoRef(), i18n.formatPhrase(RenderingI18nContext.GENERAL_TYPE), i18n.formatPhrase(RenderingI18nContext.SD_GRID_HEAD_TYPE_DESC), null, 100));
719    model.getTitles().add(new Title(null, model.getDocoRef(), i18n.formatPhrase(RenderingI18nContext.GENERAL_DESC_CONST), i18n.formatPhrase(RenderingI18nContext.SD_HEAD_DESC_DESC), null, 0));
720    if (isLogical) {
721      model.getTitles().add(new Title(null, prefix+"structuredefinition.html#logical", "Implemented As", "How this logical data item is implemented in a concrete resource", null, 0));
722    }
723    return model;
724  }
725
726  public TableModel initComparisonTable(String prefix, String id) throws IOException {
727    TableModel model = new TableModel(id, true);
728    
729    model.setAlternating(true);
730    if (mode == TableGenerationMode.XML) {
731      model.setDocoImg(help16AsData());    
732    } else {
733      model.setDocoImg(Utilities.pathURL(prefix, "help16.png"));
734    }
735    model.setDocoRef(Utilities.pathURL(prefix, "formats.html#table"));    
736    model.getTitles().add(new Title(null, model.getDocoRef(), i18n.formatPhrase(RenderingI18nContext.GENERAL_NAME), i18n.formatPhrase(RenderingI18nContext.GENERAL_LOGICAL_NAME), null, 0));
737    model.getTitles().add(new Title(null, model.getDocoRef(), i18n.formatPhrase(RenderingI18nContext.SD_COMP_HEAD_FLAGS_L), i18n.formatPhrase(RenderingI18nContext.SD_COMP_HEAD_FLAGS_L_DESC), null, 0).setStyle("border-left: 1px grey solid"));
738    model.getTitles().add(new Title(null, model.getDocoRef(), i18n.formatPhrase(RenderingI18nContext.SD_COMP_HEAD_CARD_L), i18n.formatPhrase(RenderingI18nContext.SD_COMP_HEAD_CARD_L_DESC), null, 0));
739    model.getTitles().add(new Title(null, model.getDocoRef(), i18n.formatPhrase(RenderingI18nContext.SD_COMP_HEAD_TYPE_L), i18n.formatPhrase(RenderingI18nContext.SD_COMP_HEAD_TYPE_L_DESC), null, 100));
740    model.getTitles().add(new Title(null, model.getDocoRef(), i18n.formatPhrase(RenderingI18nContext.SD_COMP_HEAD_DESC_L), i18n.formatPhrase(RenderingI18nContext.SD_COMP_HEAD_DESC_L_DESC), null, 0).setStyle("border-right: 1px grey solid"));
741    model.getTitles().add(new Title(null, model.getDocoRef(), i18n.formatPhrase(RenderingI18nContext.SD_COMP_HEAD_FLAGS_R), i18n.formatPhrase(RenderingI18nContext.SD_COMP_HEAD_FLAGS_R_DESC), null, 0).setStyle("border-left: 1px grey solid"));
742    model.getTitles().add(new Title(null, model.getDocoRef(), i18n.formatPhrase(RenderingI18nContext.SD_COMP_HEAD_CARD_R), i18n.formatPhrase(RenderingI18nContext.SD_COMP_HEAD_CARD_R_DESC), null, 0));
743    model.getTitles().add(new Title(null, model.getDocoRef(), i18n.formatPhrase(RenderingI18nContext.SD_COMP_HEAD_TYPE_R), i18n.formatPhrase(RenderingI18nContext.SD_COMP_HEAD_TYPE_R_DESC), null, 100));
744    model.getTitles().add(new Title(null, model.getDocoRef(), i18n.formatPhrase(RenderingI18nContext.SD_COMP_HEAD_DESC_R), i18n.formatPhrase(RenderingI18nContext.SD_COMP_HEAD_DESC_R_DESC), null, 0).setStyle("border-right: 1px grey solid"));
745    model.getTitles().add(new Title(null, model.getDocoRef(), i18n.formatPhrase(RenderingI18nContext.GENERAL_COMMENTS), i18n.formatPhrase(RenderingI18nContext.SD_COMP_HEAD_COMP_DESC), null, 0));
746    return model;
747  }
748
749
750
751  public TableModel initGridTable(String prefix, String id) {
752    TableModel model = new TableModel(id, false);
753    model.getTitles().add(new Title(null, model.getDocoRef(), i18n.formatPhrase(RenderingI18nContext.GENERAL_NAME), i18n.formatPhrase(RenderingI18nContext.SD_GRID_HEAD_NAME_DESC), null, 0));
754    model.getTitles().add(new Title(null, model.getDocoRef(), i18n.formatPhrase(RenderingI18nContext.GENERAL_CARD), i18n.formatPhrase(RenderingI18nContext.SD_GRID_HEAD_CARD_DESC), null, 0));
755    model.getTitles().add(new Title(null, model.getDocoRef(), i18n.formatPhrase(RenderingI18nContext.GENERAL_TYPE), i18n.formatPhrase(RenderingI18nContext.SD_GRID_HEAD_TYPE_DESC), null, 100));
756    model.getTitles().add(new Title(null, model.getDocoRef(), i18n.formatPhrase(RenderingI18nContext.SD_GRID_HEAD_DESC), i18n.formatPhrase(RenderingI18nContext.SD_GRID_HEAD_DESC_DESC), null, 0));
757    
758    return model;
759  }
760
761  public XhtmlNode generate(TableModel model, String imagePath, int border, Set<String> outputTracker) throws IOException, FHIRException  {
762    checkModel(model);
763    XhtmlNode table = new XhtmlNode(NodeType.Element, "table").setAttribute("border", Integer.toString(border)).setAttribute("cellspacing", "0").setAttribute("cellpadding", "0");
764    
765    if (model.isActive()) {      
766      table.setAttribute("id", model.getId());
767    }
768    table.setAttribute("style", "border: " + border + "px #F0F0F0 solid; font-size: 11px; font-family: verdana; vertical-align: top;");
769    XhtmlNode tr = table.addTag("tr");
770    tr.setAttribute("style", "border: " + Integer.toString(1 + border) + "px #F0F0F0 solid; font-size: 11px; font-family: verdana; vertical-align: top");
771    XhtmlNode tc = null;
772    for (Title t : model.getTitles()) {
773      tc = renderCell(tr, t, "th", null, null, null, false, null, "white", 0, imagePath, border, outputTracker, model, null, true);
774      if (t.width != 0)
775        tc.setAttribute("style", "width: "+Integer.toString(t.width)+"px");
776    }
777    if (tc != null && model.getDocoRef() != null) {
778      XhtmlNode a = tc.addTag("span").setAttribute("style", "float: right").addTag("a").setAttribute("title", "Legend for this format").setAttribute("href", model.getDocoRef());
779      if (mode == TableGenerationMode.XHTML) {
780        a.setAttribute("no-external", "true");
781      }
782      XhtmlNode img = a.addTag("img");
783      img.setAttribute("alt", "doco").setAttribute("style", "background-color: inherit").setAttribute("src", model.getDocoImg());
784      if (model.isActive()) {
785        img.setAttribute("onLoad", "fhirTableInit(this)");
786      }
787    }
788      
789    Counter counter = new Counter();
790    for (Row r : model.getRows()) {
791      renderRow(table, r, 0, new ArrayList<Integer>(), imagePath, border, outputTracker, counter, model);
792    }
793    if (model.getDocoRef() != null) {
794      tr = table.addTag("tr");
795      tc = tr.addTag("td");
796      tc.setAttribute("class", "hierarchy");
797      tc.setAttribute("colspan", Integer.toString(model.getTitles().size()));
798      tc.addTag("br");
799      XhtmlNode a = tc.addTag("a").setAttribute("title", i18n.formatPhrase(RenderingI18nContext.SD_LEGEND)).setAttribute("href", model.getDocoRef());
800      if (model.getDocoImg() != null)
801        a.addTag("img").setAttribute("alt", "doco").setAttribute("style", "background-color: inherit").setAttribute("src", model.getDocoImg());
802      a.addText(" "+i18n.formatPhrase(RenderingI18nContext.SD_DOCO));
803    }
804    return table;
805  }
806
807
808  private void renderRow(XhtmlNode table, Row r, int indent, List<Integer> indents, String imagePath, int border, Set<String> outputTracker, Counter counter, TableModel model) throws IOException  {
809    counter.row();
810    XhtmlNode tr = table.addTag("tr");
811    String color = "white";
812    if (r.getColor() != null)
813      color = r.getColor();
814    else if (model.isAlternating()  && counter.isOdd())
815      color = BACKGROUND_ALT_COLOR;
816    
817    tr.setAttribute("style", "border: " + border + "px #F0F0F0 solid; padding:0px; vertical-align: top; background-color: "+color+(r.getOpacity() == null ? "" : "; opacity: "+r.getOpacity()));
818    if (model.isActive()) {
819      tr.setAttribute("id", r.getId());
820    }
821    boolean first = true;
822    for (Cell t : r.getCells()) {
823      renderCell(tr, t, "td", first ? r.getIcon() : null, first ? r.getHint() : null, first ? indents : null, !r.getSubRows().isEmpty(), first ? r.getAnchor() : null, color, r.getLineColor(), imagePath, border, outputTracker, model, r, first);
824      first = false;
825    }
826    table.addText("\r\n");
827    
828    for (int i = 0; i < r.getSubRows().size(); i++) {
829      Row c = r.getSubRows().get(i);
830      List<Integer> ind = new ArrayList<Integer>();
831      ind.addAll(indents);
832      if (i == r.getSubRows().size() - 1) {
833        ind.add(r.getLineColor()*2);
834      } else {
835        ind.add(r.getLineColor()*2+1);
836      }
837      renderRow(table, c, indent+1, ind, imagePath, border, outputTracker, counter, model);
838    }
839  }
840
841
842  private XhtmlNode renderCell(XhtmlNode tr, Cell c, String name, String icon, String hint, List<Integer> indents, boolean hasChildren, String anchor, String color, int lineColor, String imagePath, int border, Set<String> outputTracker, TableModel table, Row row, boolean suppressExternals) throws IOException  {
843    XhtmlNode tc = tr.addTag(name);
844    tc.setAttribute("class", "hierarchy");
845    if (c.span > 1) {
846      tc.colspan(Integer.toString(c.span));
847    }
848    if (c.getId() != null) {
849      tc.setAttribute("id", c.getId());
850    }
851
852    if (indents != null) {
853      tc.addTag("img").setAttribute("src", srcFor(imagePath, "tbl_spacer.png")).setAttribute("style", "background-color: inherit").setAttribute("class", "hierarchy").setAttribute("alt", ".");
854      tc.setAttribute("style", "vertical-align: top; text-align : left; "+(c.cellStyle != null  && c.cellStyle.contains("background-color") ? "" : "background-color: "+color+"; ")+"border: "+ border +"px #F0F0F0 solid; padding:0px 4px 0px 4px; white-space: nowrap; background-image: url("+imagePath+checkExists(indents, hasChildren, lineColor, outputTracker)+")"+(c.cellStyle != null ? ";"+c.cellStyle : ""));
855      for (int i = 0; i < indents.size()-1; i++) {
856        switch (indents.get(i)) {
857          case NEW_REGULAR:
858          case NEW_SLICER:
859          case NEW_SLICE:
860            tc.addTag("img").setAttribute("src", srcFor(imagePath, "tbl_blank.png")).setAttribute("style", "background-color: inherit").setAttribute("class", "hierarchy").setAttribute("alt", ".");
861            break;
862          case CONTINUE_REGULAR:
863            tc.addTag("img").setAttribute("src", srcFor(imagePath, "tbl_vline.png")).setAttribute("style", "background-color: inherit").setAttribute("class", "hierarchy").setAttribute("alt", ".");
864            break;
865          case CONTINUE_SLICER:
866            tc.addTag("img").setAttribute("src", srcFor(imagePath, "tbl_vline_slicer.png")).setAttribute("style", "background-color: inherit").setAttribute("class", "hierarchy").setAttribute("alt", ".");
867            break;
868          case CONTINUE_SLICE:
869            tc.addTag("img").setAttribute("src", srcFor(imagePath, "tbl_vline_slice.png")).setAttribute("style", "background-color: inherit").setAttribute("class", "hierarchy").setAttribute("alt", ".");
870            break;
871          default:
872            throw new Error("Unrecognized indent level: " + indents.get(i));
873        }
874      }
875      if (!indents.isEmpty()) {
876        String sfx = table.isActive() && hasChildren ? "-open" : "";
877        XhtmlNode img = tc.addTag("img");
878        switch (indents.get(indents.size()-1)) {
879        case NEW_REGULAR:
880          img.setAttribute("src", srcFor(imagePath, "tbl_vjoin_end"+sfx+".png")).setAttribute("style", "background-color: inherit").setAttribute("class", "hierarchy").setAttribute("alt", ".");
881          break;
882        case NEW_SLICER:
883          img.setAttribute("src", srcFor(imagePath, "tbl_vjoin_end_slicer"+sfx+".png")).setAttribute("style", "background-color: inherit").setAttribute("class", "hierarchy").setAttribute("alt", ".");
884          break;
885        case NEW_SLICE:
886          img.setAttribute("src", srcFor(imagePath, "tbl_vjoin_end_slice"+sfx+".png")).setAttribute("style", "background-color: inherit").setAttribute("class", "hierarchy").setAttribute("alt", ".");
887          break;
888        case CONTINUE_REGULAR:
889          img.setAttribute("src", srcFor(imagePath, "tbl_vjoin"+sfx+".png")).setAttribute("style", "background-color: inherit").setAttribute("class", "hierarchy").setAttribute("alt", ".");
890          break;
891        case CONTINUE_SLICER:
892          img.setAttribute("src", srcFor(imagePath, "tbl_vjoin_slicer"+sfx+".png")).setAttribute("style", "background-color: inherit").setAttribute("class", "hierarchy").setAttribute("alt", ".");
893          break;
894        case CONTINUE_SLICE:
895          img.setAttribute("src", srcFor(imagePath, "tbl_vjoin_slice"+sfx+".png")).setAttribute("style", "background-color: inherit").setAttribute("class", "hierarchy").setAttribute("alt", ".");
896          break;
897        default:
898          throw new Error("Unrecognized indent level: " + indents.get(indents.size()-1));
899        }
900        if (table.isActive() && hasChildren) {
901          img.setAttribute("onClick", "tableRowAction(this)");
902        }
903      }
904    }
905    else
906      tc.setAttribute("style", "vertical-align: top; text-align : left; "+(c.cellStyle != null  && c.cellStyle.contains("background-color") ? "" : "background-color: "+color+"; ")+"border: "+ border +"px #F0F0F0 solid; padding:0px 4px 0px 4px"+(c.cellStyle != null ? ";"+c.cellStyle : ""));
907    if (!Utilities.noString(icon)) {
908      XhtmlNode img = tc.addTag("img").setAttribute("alt", "icon").setAttribute("src", srcFor(imagePath, icon)).setAttribute("class", "hierarchy").setAttribute("style", "background-color: "+color+"; background-color: inherit").setAttribute("alt", ".");
909      if (hint != null)
910        img.setAttribute("title", hint);
911      tc.addText(" ");
912    }
913    for (Piece p : c.pieces) {
914      if (!Utilities.noString(p.getTag())) {
915        XhtmlNode tag = tc.addTag(p.getTag());
916        if (p.attributes != null)
917          for (String n : p.attributes.keySet())
918            tag.setAttribute(n, p.attributes.get(n));
919        if (p.getHint() != null)
920          tag.setAttribute("title", p.getHint());
921        addStyle(tag, p);
922        if (p.hasChildren()) {
923          tag.addChildNodes(p.getChildren());
924        }
925      } else if (!Utilities.noString(p.getReference())) {
926        XhtmlNode a = addStyle(tc.addTag("a"), p);
927        a.setAttribute("href", prefixLocalHref(p.getReference()));
928        if (mode == TableGenerationMode.XHTML && suppressExternals) {
929          a.setAttribute("no-external", "true");
930        }
931        if (!Utilities.noString(p.getHint()))
932          a.setAttribute("title", p.getHint());
933        if (p.getText() != null) {
934          a.addText(p.getText());
935        } else {
936          a.addChildren(p.getChildren());
937        }
938        addStyle(a, p);
939        if (p.getTagImg() != null) {
940          a.tx(" ");
941          a.img(p.getTagImg(), null);
942        }
943        
944        if (p.hasChildren()) {
945          tc.addChildNodes(p.getChildren());
946        }
947      } else { 
948        if (!Utilities.noString(p.getHint())) {
949          XhtmlNode s = addStyle(tc.addTag("span"), p);
950          s.setAttribute("title", p.getHint());
951          s.addText(p.getText());
952        } else if (p.getStyle() != null) {
953          XhtmlNode s = addStyle(tc.addTag("span"), p);
954          s.addText(p.getText());
955        } else {
956          tc.addText(p.getText());
957        }
958        if (p.hasChildren()) {
959          tc.addChildNodes(p.getChildren());
960        }
961        if (p.getTagImg() != null) {
962          tc.tx(" ");
963          tc.img(p.getTagImg(), null);
964        }
965      }
966    }
967    if (makeTargets && !Utilities.noString(anchor)) {
968      tc.addTag("a").setAttribute("name", prefixAnchor(nmTokenize(anchor))).addText(" ");
969    }
970    return tc;
971  }
972
973
974  private XhtmlNode addStyle(XhtmlNode node, Piece p) {
975    if (p.getStyle() != null)
976      node.setAttribute("style", p.getStyle());
977    return node;
978  }
979
980  private String nmTokenize(String anchor) {
981    return anchor.replace("[", "_").replace("]", "_");
982  }
983  
984  private String srcFor(String corePrefix, String filename) throws IOException {
985    if (inLineGraphics) {
986      if (files.containsKey(filename))
987        return files.get(filename);
988      StringBuilder b = new StringBuilder();
989      b.append("data:image/png;base64,");
990      byte[] bytes;
991      File file = ManagedFileAccess.file(Utilities.path(dest, filename));
992      if (!file.exists()) // because sometime this is called real early before the files exist. it will be built again later because of this
993        bytes = new byte[0]; 
994      else
995        bytes = FileUtils.readFileToByteArray(file);
996      b.append(new String(Base64.encodeBase64(bytes)));
997//      files.put(filename, b.toString());
998      return b.toString();
999    } else
1000      return corePrefix+filename;
1001  }
1002
1003  public static String help16AsData() throws IOException {
1004    ClassLoader classLoader = HierarchicalTableGenerator.class.getClassLoader();
1005    InputStream help = classLoader.getResourceAsStream("help16.png");
1006    StringBuilder b = new StringBuilder();
1007    b.append("data:image/png;base64,");
1008    byte[] bytes = TextFile.streamToBytes(help);
1009    b.append(new String(Base64.encodeBase64(bytes)));
1010    return b.toString();
1011  }
1012  
1013  private void checkModel(TableModel model) throws FHIRException  {
1014    check(!model.getTitles().isEmpty(), "Must have titles");
1015    int tc = 0;
1016    for (Cell c : model.getTitles()) {
1017      check(c);
1018      tc = tc + c.span;
1019    }
1020    int i = 0;
1021    for (Row r : model.getRows()) { 
1022      check(r, "rows", tc, "", i, model.getRows().size());
1023      i++;
1024    }
1025  }
1026
1027
1028  private void check(Cell c) throws FHIRException  {  
1029    boolean hasText = false;
1030    for (Piece p : c.pieces)
1031      if (!Utilities.noString(p.getText()))
1032        hasText = true;
1033    check(hasText, "Title cells must have text");    
1034  }
1035
1036
1037  private void check(Row r, String string, int size, String path, int index, int total) throws FHIRException  {
1038    String id = Integer.toString(index)+".";
1039    if (total <= 26) {
1040      char c = (char) ('a'+index);
1041      id = Character.toString(c);
1042    }
1043    path = path + id;
1044    r.setId(path);
1045    int tc = 0;
1046    for (Cell c : r.getCells()) {
1047      tc = tc + c.span;
1048    }
1049    if (tc != size) {
1050      check(tc == size, "All rows must have the same number of columns as the titles  ("+Integer.toString(size)+") but row "+path+" doesn't - it has "+tc+" ("+(r.getCells().size() > 0 ? "??" : r.text())+"): "+r.getCells());      
1051    }
1052    int i = 0;
1053    for (Row c : r.getSubRows()) {
1054      check(c, "rows", size, path, i, r.getSubRows().size());
1055      i++;
1056    }
1057  }
1058
1059
1060  private String checkExists(List<Integer> indents, boolean hasChildren, int lineColor, Set<String> outputTracker) throws IOException  {
1061    String filename = makeName(indents);
1062    
1063    StringBuilder b = new StringBuilder();
1064    if (inLineGraphics) {
1065      if (files.containsKey(filename))
1066        return files.get(filename);
1067      ByteArrayOutputStream bytes = new ByteArrayOutputStream();
1068      genImage(indents, hasChildren, lineColor, bytes);
1069      b.append("data:image/png;base64,");
1070      byte[] encodeBase64 = Base64.encodeBase64(bytes.toByteArray());
1071      b.append(new String(encodeBase64));
1072      files.put(filename, b.toString());
1073      return b.toString();
1074    } else {
1075      b.append("tbl_bck");
1076      for (Integer i : indents)
1077        b.append(Integer.toString(i));
1078      int indent = lineColor*2 + (hasChildren?1:0);
1079      b.append(Integer.toString(indent));
1080      b.append(".png");
1081      String file = Utilities.path(dest, b.toString());
1082      if (!ManagedFileAccess.file(file).exists()) {
1083        File newFile = ManagedFileAccess.file(file);
1084        if (newFile.getParentFile() == null) {
1085          throw new Error("No source directory provided. ("+file+")");
1086        } else {
1087          newFile.getParentFile().mkdirs();
1088        }
1089        newFile.createNewFile();
1090        FileOutputStream stream = ManagedFileAccess.outStream(file);
1091        try {
1092          genImage(indents, hasChildren, lineColor, stream);
1093          if (outputTracker!=null)
1094            outputTracker.add(file);
1095        } finally {
1096          stream.close();
1097        }
1098      }
1099      return b.toString();
1100    }
1101  }
1102
1103
1104  private void genImage(List<Integer> indents, boolean hasChildren, int lineColor, OutputStream stream) throws IOException {
1105    BufferedImage bi = new BufferedImage(800, 2, BufferedImage.TYPE_INT_ARGB);
1106    // i have no idea why this works to make these pixels transparent. It defies logic. 
1107    // But this combination of INT_ARGB and filling with grey magically worked when nothing else did. So it stays as is.
1108    Color grey = new Color(99,99,99,0); 
1109    for (int i = 0; i < 800; i++) {
1110      bi.setRGB(i, 0, grey.getRGB());
1111      bi.setRGB(i, 1, grey.getRGB());
1112    }
1113    Color black = new Color(0, 0, 0);
1114    Color green = new Color(14,209,69);
1115    Color gold = new Color(212,168,21);
1116    for (int i = 0; i < indents.size(); i++) {
1117      int indent = indents.get(i).intValue();
1118      if (indent == CONTINUE_REGULAR)
1119        bi.setRGB(12+(i*16), 0, black.getRGB());
1120      else if (indent == CONTINUE_SLICER)
1121        bi.setRGB(12+(i*16), 0, green.getRGB());
1122      else if (indent == CONTINUE_SLICE)
1123        bi.setRGB(12+(i*16), 0, gold.getRGB());
1124    }
1125    if (hasChildren) {
1126      if (lineColor==0)
1127        bi.setRGB(12+(indents.size()*16), 0, black.getRGB());
1128      else if (lineColor==1)
1129        bi.setRGB(12+(indents.size()*16), 0, green.getRGB());
1130      else if (lineColor==2)
1131        bi.setRGB(12+(indents.size()*16), 0, gold.getRGB());
1132    }
1133    ImageIO.write(bi, "PNG", stream);
1134  }
1135
1136  private String makeName(List<Integer> indents) {
1137    StringBuilder b = new StringBuilder();
1138    b.append("indents:");
1139    for (Integer i : indents)
1140      b.append(Integer.toString(i));
1141    return b.toString();
1142  }
1143
1144  private void check(boolean check, String message) throws FHIRException  {
1145    if (!check)
1146      throw new FHIRException(message);
1147  }
1148
1149  public void emptyRow(TableModel model, int cellCount) {
1150    Row r = new Row();
1151    model.rows.add(r);
1152    for (int i = 0; i < cellCount; i++) {
1153      r.getCells().add(new Cell());
1154    }
1155  }
1156  
1157
1158  public String getUniqueLocalPrefix() {
1159    return uniqueLocalPrefix;
1160  }
1161
1162  public void setUniqueLocalPrefix(String uniqueLocalPrefix) {
1163    if (Utilities.noString(uniqueLocalPrefix)) {
1164      throw new Error("what?");
1165    }
1166    this.uniqueLocalPrefix = uniqueLocalPrefix;
1167  }
1168
1169  public String prefixAnchor(String anchor) {
1170    return Utilities.noString(uniqueLocalPrefix) ? anchor : uniqueLocalPrefix+"-" + anchor;
1171  }
1172
1173  public String prefixLocalHref(String url) {
1174    if (url == null || Utilities.noString(uniqueLocalPrefix) || !url.startsWith("#")) {
1175      return url;
1176    }
1177    return "#"+uniqueLocalPrefix+"-"+url.substring(1);
1178  }
1179  
1180}