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.FileUtilities;
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 Piece setTag(String tag) {
182      this.tag = tag;
183      return this;
184    }
185
186    public Piece setText(String text) {
187      this.text = text;
188      return this;
189    }
190
191    public void setHint(String hint) {
192      this.hint = hint;
193    }
194
195    public Piece setStyle(String style) {
196      this.style = style;
197      return this;
198    }
199
200    public Piece addStyle(String style) {
201      if (this.style != null)
202        this.style = this.style+"; "+style;
203      else
204        this.style = style;
205      return this;
206    }
207
208    public void addToHint(String text) {
209      if (this.hint == null)
210        this.hint = text;
211      else
212        this.hint += (this.hint.endsWith(".") || this.hint.endsWith("?") ? " " : ". ")+text;
213    }
214    
215    public boolean hasChildren() {
216      return children != null && !children.isEmpty();
217    }
218
219    public XhtmlNodeList getChildren() {
220      if (children == null)
221        children = new XhtmlNodeList();
222      return children;
223    }
224
225    public Piece addHtml(XhtmlNode x) {
226      getChildren().add(x);
227      return this;
228    }
229    
230    public Piece attr(String name, String value) {
231      if (attributes == null) {
232        attributes = new HashMap<>();
233      }
234      attributes.put(name, value);
235      return this;
236    }
237
238    public String getTagImg() {
239      return tagImg;
240    }
241
242    public Piece setTagImg(String tagImg) {
243      this.tagImg = tagImg;
244      return this;
245    }
246    
247  }
248  
249  public class Cell {
250    private List<Piece> pieces = new ArrayList<HierarchicalTableGenerator.Piece>();
251    private String cellStyle;
252    protected int span = 1;
253    private boolean innerTable; // if you want a multiline left cell, you have to set this to true
254    private TextAlignment alignment = TextAlignment.LEFT;
255    private String id;
256 
257    public Cell() {
258      
259    }
260    public Cell(String prefix, String reference, String text, String hint, String suffix) {
261      super();
262      if (!Utilities.noString(prefix))
263        pieces.add(new Piece(null, prefix, null));
264      pieces.add(new Piece(reference, text, hint));
265      if (!Utilities.noString(suffix))
266        pieces.add(new Piece(null, suffix, null));
267    }
268    public List<Piece> getPieces() {
269      return pieces;
270    }
271    public Cell addPiece(Piece piece) {
272      pieces.add(piece);
273      return this;
274    }
275    
276    public Cell addMarkdown(String md) {
277      return addMarkdown(md, null);
278    }
279    
280    public Cell addMarkdown(String md, String style) {
281      if (!Utilities.noString(md)) {
282        try {
283          Parser parser = Parser.builder().build();
284          Node document = parser.parse(md);
285          HtmlRenderer renderer = HtmlRenderer.builder().escapeHtml(true).build();
286          String html = renderer.render(document);  
287          pieces.addAll(htmlToParagraphPieces(html, style));
288        } catch (Exception e) {
289          e.printStackTrace();
290        }
291      }
292      return this;
293    }
294    
295    public Cell addMarkdownNoPara(String md) {
296      return addMarkdownNoPara(md, null);
297    }
298    
299    public Cell addMarkdownNoPara(String md, String style) {
300      try {
301        Parser parser = Parser.builder().build();
302        Node document = parser.parse(md);
303        HtmlRenderer renderer = HtmlRenderer.builder().escapeHtml(true).build();
304        String html = renderer.render(document);  
305        pieces.addAll(htmlToParagraphPieces(html, style));
306      } catch (Exception e) {
307        e.printStackTrace();
308      }
309      return this;
310    }
311    
312    private List<Piece> htmlToParagraphPieces(String html, String style)  {
313      List<Piece> myPieces = new ArrayList<Piece>();
314      try {
315        XhtmlNode node = new XhtmlParser().parseFragment("<html>"+html+"</html>");
316        boolean first = true;
317        for (XhtmlNode c : node.getChildNodes()) {
318          if (first) {
319            first = false;
320          } else {
321            myPieces.add(new Piece("br"));
322            myPieces.add(new Piece("br"));            
323          }
324          if (c.getNodeType() == NodeType.Text) {
325            if (!StringUtils.isWhitespace(c.getContent()))
326              addNode(myPieces, c, style);
327          } else if ("p".equals(c.getName())) {
328            for (XhtmlNode g : c.getChildNodes()) {
329              addNode(myPieces, g, style);
330            }
331          } else {
332           Piece x = new Piece(c.getName());
333           x.getChildren().addAll(c.getChildNodes());
334           if (style != null) {
335             x.addStyle(style);
336           }
337           myPieces.add(x);            
338          }
339        }
340//        String[] paragraphs = html.replace("<p>", "").split("<\\/p>|<br  \\/>");
341//        for (int i=0;i<paragraphs.length;i++) {
342//          if (!paragraphs[i].isEmpty()) {
343//            if (i!=0) {
344//              myPieces.add(new Piece("br"));
345//              myPieces.add(new Piece("br"));
346//            }
347//            myPieces.addAll(htmlFormattingToPieces(paragraphs[i]));
348//          }
349//        }
350      } catch (Exception e) {
351        throw new FHIRException("Exception parsing html: "+e.getMessage()+" for "+html, e);
352      }
353
354      return myPieces;
355    }
356    
357    private List<Piece> htmlFormattingToPieces(String html) throws IOException, FHIRException {
358      List<Piece> myPieces = new ArrayList<Piece>();
359      if (html.contains(("<"))) {
360        XhtmlNode node = new XhtmlParser().parseFragment("<p>"+html+"</p>");
361        for (XhtmlNode c : node.getChildNodes()) {
362          addNode(myPieces, c, null);
363        }
364      } else
365        myPieces.add(new Piece(null, html, null));        
366      return myPieces;
367    }
368    
369    private void addNode(List<Piece> list, XhtmlNode c, String style) {
370      if (c.getNodeType() == NodeType.Text)
371        list.add(styleIt(new Piece(null, c.getContent(), null), style));
372      else if (c.getNodeType() == NodeType.Element) {
373        if (c.getName().equals("a")) {
374          list.add(styleIt(new Piece(c.getAttribute("href"), c.allText(), c.getAttribute("title")), style));                    
375        } else if (c.getName().equals("b") || c.getName().equals("em") || c.getName().equals("strong")) {
376          list.add(styleIt(new Piece(null, c.allText(), null).setStyle("font-face: bold"), style));                    
377        } else if (c.getName().equals("code")) {
378          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));                    
379        } else if (c.getName().equals("i")) {
380          list.add(styleIt(new Piece(null, c.allText(), null).setStyle("font-style: italic"), style));
381        } else if (c.getName().equals("pre")) {
382          Piece p = styleIt(new Piece(c.getName()).setStyle("white-space: pre; font-family: courier"), style);
383          list.add(p);
384          p.getChildren().addAll(c.getChildNodes());
385        } else if (c.getName().equals("ul") || c.getName().equals("ol")) {
386          Piece p = styleIt(new Piece(c.getName()), style);
387          list.add(p);
388          p.getChildren().addAll(c.getChildNodes());
389        } else if (c.getName().equals("i")) {
390          list.add(styleIt(new Piece(null, c.allText(), null).setStyle("font-style: italic"), style));                    
391        } else if (c.getName().equals("h1")||c.getName().equals("h2")||c.getName().equals("h3")||c.getName().equals("h4")) {
392          Piece p = styleIt(new Piece(c.getName()), style);
393          list.add(p);
394          p.getChildren().addAll(c.getChildNodes());
395        } else if (c.getName().equals("br")) {
396          list.add(styleIt(new Piece(c.getName()), style));
397        } else {
398          throw new Error("Not handled yet: "+c.getName());
399        }
400      } else
401        throw new Error("Unhandled type "+c.getNodeType().toString());
402    }
403    
404    
405    private Piece styleIt(Piece piece, String style) {
406      if (style != null) {
407        piece.addStyle(style);
408      }
409      return piece;
410    }
411
412    public Cell addStyle(String style) {
413      for (Piece p : pieces)
414        p.addStyle(style);
415      return this;
416    }
417    
418    public Cell addCellStyle(String style) {
419      if (cellStyle == null) {
420        cellStyle = style;
421      } else {
422        cellStyle = cellStyle+"; "+style;
423      }
424      return this;
425    }
426    
427    public void addToHint(String text) {
428      for (Piece p : pieces)
429        p.addToHint(text);            
430    }
431    public Piece addStyledText(String hint, String alt, String fgColor, String bgColor, String link, boolean border) {
432      Piece p = new Piece(link, alt, hint);
433      p.addStyle("padding-left: 3px");
434      p.addStyle("padding-right: 3px");
435      if (border) {
436        p.addStyle("border: 1px grey solid");
437        p.addStyle("font-weight: bold");
438      }
439      if (fgColor != null) {
440        p.addStyle("color: "+fgColor);
441        p.addStyle("background-color: "+bgColor);
442      } else {
443        p.addStyle("color: black");
444        p.addStyle("background-color: "+bgColor != null ? bgColor : "white");       
445      }
446      pieces.add(p);
447      return p;
448    }
449    public Piece addText(String text) {
450      Piece p = new Piece(null, text, null);
451      pieces.add(p);
452      return p;
453    }
454    public String text() {
455      StringBuilder b = new StringBuilder();
456      for (Piece p : pieces)
457        b.append(p.text);
458      return b.toString();
459    }
460    @Override
461    public String toString() {
462      if (span != 1) {
463        return text()+" {"+span+"}";
464      } else {
465        return text();
466      }
467    }
468    public Cell setStyle(String value) {
469      cellStyle = value;
470      return this;
471    }
472    
473    public Cell span(int value) {
474      span = value;
475      return this;
476    }
477    public Cell center() {
478      alignment = TextAlignment.CENTER;
479      return this;
480    }
481    
482    public String getId() {
483      return id;
484    }
485    public void setId(String id) {
486      this.id = id;
487    }
488    public Piece addImg(String icon, String hint, String link) {
489      Piece p = new Piece("img");
490      p.attr("src", icon);
491      p.hint = hint;
492      p.reference = link;
493      pieces.add(p);
494      return p;
495    }
496    public void addXhtml(XhtmlNode div) {
497      Piece p = new Piece(null);
498      pieces.add(p);
499      p.children = div.childNodes;
500    }
501    public boolean isInnerTable() {
502      return innerTable;
503    }
504    public void setInnerTable(boolean innerTable) {
505      this.innerTable = innerTable;
506    }
507
508  }
509
510  public class Title extends Cell {
511    private int width;
512
513    public Title(String prefix, String reference, String text, String hint, String suffix, int width) {
514      super(prefix, reference, text, hint, suffix);
515      this.width = width;
516    }
517
518    public Title(String prefix, String reference, String text, String hint, String suffix, int width, int span) {
519      super(prefix, reference, text, hint, suffix);
520      this.width = width;
521      this.span = span;
522    }
523
524    public Title setStyle(String value) {
525      super.setStyle(value);
526      return this;
527    }
528  }
529  
530  public class Row {
531    private List<Row> subRows = new ArrayList<HierarchicalTableGenerator.Row>();
532    private List<Cell> cells = new ArrayList<HierarchicalTableGenerator.Cell>();
533    private String icon;
534    private String anchor;
535    private String hint;
536    private String color;
537    private int lineColor;
538    private String id;
539    private String opacity;
540    private String topLine;
541    private boolean partnerRow;
542    
543    public List<Row> getSubRows() {
544      return subRows;
545    }
546    public List<Cell> getCells() {
547      return cells;
548    }
549    public String getIcon() {
550      return icon;
551    }
552    public void setIcon(String icon, String hint) {
553      this.icon = icon;
554      this.hint = hint;
555    }
556    public String getAnchor() {
557      return anchor;
558    }
559    public void setAnchor(String anchor) {
560      this.anchor = anchor;
561    }
562    public String getHint() {
563      return hint;
564    }
565    public String getColor() {
566      return color;
567    }
568    public void setColor(String color) {
569      this.color = color;
570    }
571    public int getLineColor() {
572      return lineColor;
573    }
574    public void setLineColor(int lineColor) {
575      assert lineColor >= 0;
576      assert lineColor <= 2;
577      this.lineColor = lineColor;
578    }
579    public String getId() {
580      return id;
581    }
582    public void setId(String id) {
583      this.id = id;
584    }
585    public String getOpacity() {
586      return opacity;
587    }
588    public void setOpacity(String opacity) {
589      this.opacity = opacity;
590    }
591    public String text() {
592      CommaSeparatedStringBuilder b = new CommaSeparatedStringBuilder();
593      for (Cell c : cells) {
594        b.append(c.text());
595      }
596      return b.toString();
597    }
598    public String getTopLine() {
599      return topLine;
600    }
601    public void setTopLine(String topLine) {
602      this.topLine = topLine;
603    }
604    
605  }
606
607  public class TableModel {
608    private String id;
609    private boolean active;
610    private List<Title> titles = new ArrayList<HierarchicalTableGenerator.Title>();
611    private List<Row> rows = new ArrayList<HierarchicalTableGenerator.Row>();
612    private String docoRef;
613    private String docoImg;
614    private boolean alternating;
615    private boolean showHeadings = true;
616    private boolean border = false;
617        
618    public TableModel(String id, boolean active) {
619      super();
620      this.id = id;
621      this.active = active;
622    }
623    public List<Title> getTitles() {
624      return titles;
625    }
626    public List<Row> getRows() {
627      return rows;
628    }
629    public String getDocoRef() {
630      return docoRef;
631    }
632    public String getDocoImg() {
633      return docoImg;
634    }
635    public void setDocoRef(String docoRef) {
636      this.docoRef = docoRef;
637    }
638    public void setDocoImg(String docoImg) {
639      this.docoImg = docoImg;
640    }
641    public String getId() {
642      return id;
643    }
644    
645    public void setId(String id) {
646      this.id = id;
647    }
648    public boolean isActive() {
649      return active && ACTIVE_TABLES;
650    }
651    public boolean isAlternating() {
652      return alternating;
653    }
654    public void setAlternating(boolean alternating) {
655      this.alternating = alternating;
656    }
657    public boolean isShowHeadings() {
658      return showHeadings;
659    }
660    public void setShowHeadings(boolean showHeadings) {
661      this.showHeadings = showHeadings;
662    }
663    public boolean isBorder() {
664      return border;
665    }
666    public void setBorder(boolean border) {
667      this.border = border;
668    }
669    
670  }
671
672
673  private String dest;
674  private boolean makeTargets;
675  private String defPath = "";
676
677  /**
678   * There are circumstances where the table has to present in the absence of a stable supporting infrastructure.
679   * and the file paths cannot be guaranteed. For these reasons, you can tell the builder to inline all the graphics
680   * (all the styles are inlined anyway, since the table fbuiler has even less control over the styling
681   *  
682   */
683  private boolean inLineGraphics;  
684  
685  private TableGenerationMode mode;
686  private RenderingI18nContext i18n;
687  private String uniqueLocalPrefix;
688  private boolean treelines = true;
689
690  public HierarchicalTableGenerator(RenderingI18nContext i18n) {
691    super();
692    this.i18n = i18n;
693  }
694
695  public HierarchicalTableGenerator(RenderingI18nContext i18n, String uniqueLocalPrefix) {
696    super();
697    this.i18n = i18n;
698    this.uniqueLocalPrefix = uniqueLocalPrefix;
699  }
700
701  public HierarchicalTableGenerator(RenderingI18nContext i18n, String dest, boolean inlineGraphics) {
702    super();
703    this.i18n = i18n;
704    this.dest = dest;
705    this.inLineGraphics = inlineGraphics;
706    this.makeTargets = true;
707    checkSetup();
708  }
709
710  public HierarchicalTableGenerator(RenderingI18nContext i18n, String dest, boolean inlineGraphics, String uniqueLocalPrefix) {
711    super();
712    this.i18n = i18n;
713    this.dest = dest;
714    this.inLineGraphics = inlineGraphics;
715    this.makeTargets = true;
716    this.uniqueLocalPrefix = uniqueLocalPrefix;
717    checkSetup();
718  }
719
720  public HierarchicalTableGenerator(RenderingI18nContext i18n, String dest, boolean inlineGraphics, boolean makeTargets, String defPath, String uniqueLocalPrefix) {
721    super();
722    this.i18n = i18n;
723    this.dest = dest;
724    this.inLineGraphics = inlineGraphics;
725    this.makeTargets = makeTargets;
726    this.defPath = defPath;
727    this.uniqueLocalPrefix = uniqueLocalPrefix;
728    checkSetup();
729  }
730
731  public HierarchicalTableGenerator(RenderingI18nContext i18n, String dest, boolean inlineGraphics, boolean makeTargets, String uniqueLocalPrefix) {
732    super();
733    this.i18n = i18n;
734    this.dest = dest;
735    this.inLineGraphics = inlineGraphics;
736    this.makeTargets = makeTargets;
737    this.uniqueLocalPrefix = uniqueLocalPrefix;
738    checkSetup();
739  }
740
741  public HierarchicalTableGenerator(RenderingI18nContext i18n, String dest, boolean inlineGraphics, boolean makeTargets) {
742    super();
743    this.i18n = i18n;
744    this.dest = dest;
745    this.inLineGraphics = inlineGraphics;
746    this.makeTargets = makeTargets;
747    checkSetup();
748  }
749
750  private void checkSetup() {
751    if (dest == null) {
752      throw new Error("what");
753    }
754  }
755
756  public String getDefPath() {
757    return defPath;
758  }
759
760  public TableModel initNormalTable(String prefix, boolean isLogical, boolean alternating, String id, boolean isActive, TableGenerationMode mode) throws IOException {
761    this.mode = mode;
762    
763    TableModel model = new TableModel(id, isActive);
764    
765    model.setAlternating(alternating);
766    if (mode == TableGenerationMode.XML) {
767      model.setDocoImg(help16AsData());     
768    } else {
769      model.setDocoImg(Utilities.pathURL(prefix, "help16.png"));
770    }
771    model.setDocoRef(Utilities.pathURL("https://build.fhir.org/ig/FHIR/ig-guidance", "readingIgs.html#table-views"));
772    model.getTitles().add(new Title(null, model.getDocoRef(), i18n.formatPhrase(RenderingI18nContext.GENERAL_NAME), i18n.formatPhrase(RenderingI18nContext.GENERAL_LOGICAL_NAME), null, 0));
773    model.getTitles().add(new Title(null, model.getDocoRef(), i18n.formatPhrase(RenderingI18nContext.GENERAL_FLAGS), i18n.formatPhrase(RenderingI18nContext.SD_HEAD_FLAGS_DESC), null, 0));
774    model.getTitles().add(new Title(null, model.getDocoRef(), i18n.formatPhrase(RenderingI18nContext.GENERAL_CARD), i18n.formatPhrase(RenderingI18nContext.SD_HEAD_CARD_DESC), null, 0));
775    model.getTitles().add(new Title(null, model.getDocoRef(), i18n.formatPhrase(RenderingI18nContext.GENERAL_TYPE), i18n.formatPhrase(RenderingI18nContext.SD_GRID_HEAD_TYPE_DESC), null, 100));
776    model.getTitles().add(new Title(null, model.getDocoRef(), i18n.formatPhrase(RenderingI18nContext.GENERAL_DESC_CONST), i18n.formatPhrase(RenderingI18nContext.SD_HEAD_DESC_DESC), null, 0));
777    if (isLogical) {
778      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));
779    }
780    return model;
781  }
782
783
784  public TableModel initComparisonTable(String prefix, String id) throws IOException {
785    TableModel model = new TableModel(id, true);
786    
787    model.setAlternating(true);
788    if (mode == TableGenerationMode.XML) {
789      model.setDocoImg(help16AsData());    
790    } else {
791      model.setDocoImg(Utilities.pathURL(prefix, "help16.png"));
792    }
793    model.setDocoRef(Utilities.pathURL(prefix, "formats.html#table"));    
794    model.getTitles().add(new Title(null, model.getDocoRef(), i18n.formatPhrase(RenderingI18nContext.GENERAL_NAME), i18n.formatPhrase(RenderingI18nContext.GENERAL_LOGICAL_NAME), null, 0));
795    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"));
796    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));
797    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));
798    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"));
799    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"));
800    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));
801    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));
802    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"));
803    model.getTitles().add(new Title(null, model.getDocoRef(), i18n.formatPhrase(RenderingI18nContext.GENERAL_COMMENTS), i18n.formatPhrase(RenderingI18nContext.SD_COMP_HEAD_COMP_DESC), null, 0));
804    return model;
805  }
806
807
808
809  public TableModel initGridTable(String prefix, String id) {
810    TableModel model = new TableModel(id, false);
811    model.getTitles().add(new Title(null, model.getDocoRef(), i18n.formatPhrase(RenderingI18nContext.GENERAL_NAME), i18n.formatPhrase(RenderingI18nContext.SD_GRID_HEAD_NAME_DESC), null, 0));
812    model.getTitles().add(new Title(null, model.getDocoRef(), i18n.formatPhrase(RenderingI18nContext.GENERAL_CARD), i18n.formatPhrase(RenderingI18nContext.SD_GRID_HEAD_CARD_DESC), null, 0));
813    model.getTitles().add(new Title(null, model.getDocoRef(), i18n.formatPhrase(RenderingI18nContext.GENERAL_TYPE), i18n.formatPhrase(RenderingI18nContext.SD_GRID_HEAD_TYPE_DESC), null, 100));
814    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));
815    
816    return model;
817  }
818
819  public XhtmlNode generate(TableModel model, String imagePath, int border, Set<String> outputTracker) throws IOException, FHIRException  {
820    checkModel(model);
821    XhtmlNode table = new XhtmlNode(NodeType.Element, "table").setAttribute("border", Integer.toString(border)).setAttribute("cellspacing", "0").setAttribute("cellpadding", "0");
822    if (model.active) {
823      table.setAttribute("fhir", "generated-heirarchy"); // deprecated - will be removed once everyone has dealt with the change
824      table.setAttribute("data-fhir", "generated-heirarchy");
825    }
826    if (model.isActive()) {      
827      table.setAttribute("id", model.getId());
828    }
829    if (model.isBorder()) {
830      table.setAttribute("style", "border: 2px black solid; font-size: 11px; font-family: verdana; vertical-align: top;");
831    } else {
832      table.setAttribute("style", "border: " + border + "px #F0F0F0 solid; font-size: 11px; font-family: verdana; vertical-align: top;");
833    }
834    if (model.isShowHeadings()) {
835      XhtmlNode tr = table.addTag("tr");
836      if (model.active) {
837        tr.setAttribute("fhir", "generated-heirarchy"); // deprecated - will be removed once everyone has dealt with the change
838        tr.setAttribute("data-fhir", "generated-heirarchy");
839      }
840      tr.setAttribute("style", "border: " + Integer.toString(1 + border) + "px #F0F0F0 solid; font-size: 11px; font-family: verdana; vertical-align: top");
841      XhtmlNode tc = null;
842      for (Title t : model.getTitles()) {
843        tc = renderCell(tr, t, "th", null, null, null, false, null, "white", 0, imagePath, border, outputTracker, model, null, true);
844        if (t.width != 0)
845          tc.setAttribute("style", "width: "+Integer.toString(t.width)+"px");
846      }
847      if (tc != null && model.getDocoRef() != null) {
848        XhtmlNode a = tc.addTag("span").setAttribute("style", "float: right").addTag("a").setAttribute("title", "Legend for this format").setAttribute("href", model.getDocoRef());
849        if (mode == TableGenerationMode.XHTML) {
850          a.setAttribute("no-external", "true"); // deprecated - will be removed once everyone has dealt with the change
851          a.setAttribute("data-no-external", "true");
852        }
853        XhtmlNode img = a.addTag("img");
854        img.setAttribute("alt", "doco").setAttribute("style", "background-color: inherit").setAttribute("src", model.getDocoImg());
855        if (model.isActive()) {
856          img.setAttribute("onLoad", "fhirTableInit(this)");
857        }
858      }
859    }
860    Counter counter = new Counter();
861    for (Row r : model.getRows()) {
862      renderRow(table, r, 0, new ArrayList<Integer>(), imagePath, border, outputTracker, counter, model);
863    }
864    if (model.getDocoRef() != null) {
865      XhtmlNode tr = table.addTag("tr");
866      if (model.active) {
867        tr.setAttribute("fhir", "generated-heirarchy"); // deprecated - will be removed once everyone has dealt with the change
868        tr.setAttribute("data-fhir", "generated-heirarchy");
869      }
870      XhtmlNode tc = tr.addTag("td");
871      tc.setAttribute("class", "hierarchy");
872      tc.setAttribute("colspan", Integer.toString(model.getTitles().size()));
873      tc.addTag("br");
874      XhtmlNode a = tc.addTag("a").setAttribute("title", i18n.formatPhrase(RenderingI18nContext.SD_LEGEND)).setAttribute("href", model.getDocoRef());
875      if (model.getDocoImg() != null)
876        a.addTag("img").setAttribute("alt", "doco").setAttribute("style", "background-color: inherit").setAttribute("src", model.getDocoImg());
877      a.addText(" "+i18n.formatPhrase(RenderingI18nContext.SD_DOCO));
878    }
879    return table;
880  }
881
882
883  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  {
884    if (!r.partnerRow) {
885      counter.row();
886    }
887    XhtmlNode tr = table.addTag("tr");
888    if (model.active) {
889      tr.setAttribute("fhir", "generated-heirarchy"); // deprecated - will be removed once everyone has dealt with the change
890      tr.setAttribute("data-fhir", "generated-heirarchy");
891    }
892    
893    String color = "white";
894    if (r.getColor() != null)
895      color = r.getColor();
896    else if (model.isAlternating()  && counter.isOdd())
897      color = BACKGROUND_ALT_COLOR;
898    
899    String lineStyle = r.getTopLine() == null ? "" : "; border-top: 1px solid "+r.getTopLine();
900    
901    tr.setAttribute("style", "border: " + border + "px #F0F0F0 solid; padding:0px; vertical-align: top; background-color: "+color+(r.getOpacity() == null ? "" : "; opacity: "+r.getOpacity())+lineStyle);
902    if (model.isActive()) {
903      tr.setAttribute("id", r.getId());
904    }
905    boolean first = true;
906    for (Cell t : r.getCells()) {
907      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);
908      first = false;
909    }
910    table.addText("\r\n");
911    
912    for (int i = 0; i < r.getSubRows().size(); i++) {
913      Row c = r.getSubRows().get(i);
914      List<Integer> ind = new ArrayList<Integer>();
915      ind.addAll(indents);
916      if (i == r.getSubRows().size() - 1) {
917        ind.add(r.getLineColor()*2);
918      } else {
919        ind.add(r.getLineColor()*2+1);
920      }
921      renderRow(table, c, indent+1, ind, imagePath, border, outputTracker, counter, model);
922    }
923  }
924
925
926  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  {
927    XhtmlNode tc = tr.addTag(name);
928    tc.setAttribute("class", "hierarchy");
929    if (c.span > 1) {
930      tc.colspan(Integer.toString(c.span));
931    }
932    if (c.getId() != null) {
933      tc.setAttribute("id", c.getId());
934    }    
935    String lineStyle = row != null && row.getTopLine() == null ? "" : "; padding-top: 3px; padding-bottom: 3px";
936
937    XhtmlNode itc = tc;
938    XhtmlNode itr = null;
939    if (c.innerTable) {
940      itr = tc.table("none", true).tr();
941      itc = itr.td();
942    }
943
944    if (indents != null) {
945      itc.addTag("img").setAttribute("src", srcFor(imagePath, "tbl_spacer.png")).setAttribute("style", "background-color: inherit").setAttribute("class", "hierarchy").setAttribute("alt", ".");
946      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"+(treelines ? "; background-image: url("+imagePath+checkExists(indents, hasChildren, lineColor, outputTracker)+")" : "")+(c.cellStyle != null ? ";"+c.cellStyle : "")+lineStyle);
947      for (int i = 0; i < indents.size()-1; i++) {
948        switch (indents.get(i)) {
949          case NEW_REGULAR:
950          case NEW_SLICER:
951          case NEW_SLICE:
952            itc.addTag("img").setAttribute("src", srcFor(imagePath, "tbl_blank.png")).setAttribute("style", "background-color: inherit").setAttribute("class", "hierarchy").setAttribute("alt", ".");
953            break;
954          case CONTINUE_REGULAR:
955            itc.addTag("img").setAttribute("src", srcFor(imagePath, "tbl_vline.png")).setAttribute("style", "background-color: inherit").setAttribute("class", "hierarchy").setAttribute("alt", ".");
956            break;
957          case CONTINUE_SLICER:
958            itc.addTag("img").setAttribute("src", srcFor(imagePath, "tbl_vline_slicer.png")).setAttribute("style", "background-color: inherit").setAttribute("class", "hierarchy").setAttribute("alt", ".");
959            break;
960          case CONTINUE_SLICE:
961            itc.addTag("img").setAttribute("src", srcFor(imagePath, "tbl_vline_slice.png")).setAttribute("style", "background-color: inherit").setAttribute("class", "hierarchy").setAttribute("alt", ".");
962            break;
963          default:
964            throw new Error("Unrecognized indent level: " + indents.get(i));
965        }
966      }
967      if (!indents.isEmpty()) {
968        String sfx = table.isActive() && hasChildren ? "-open" : "";
969        XhtmlNode img = itc.addTag("img");
970        switch (indents.get(indents.size()-1)) {
971        case NEW_REGULAR:
972          img.setAttribute("src", srcFor(imagePath, "tbl_vjoin_end"+sfx+".png")).setAttribute("style", "background-color: inherit").setAttribute("class", "hierarchy").setAttribute("alt", ".");
973          break;
974        case NEW_SLICER:
975          img.setAttribute("src", srcFor(imagePath, "tbl_vjoin_end_slicer"+sfx+".png")).setAttribute("style", "background-color: inherit").setAttribute("class", "hierarchy").setAttribute("alt", ".");
976          break;
977        case NEW_SLICE:
978          img.setAttribute("src", srcFor(imagePath, "tbl_vjoin_end_slice"+sfx+".png")).setAttribute("style", "background-color: inherit").setAttribute("class", "hierarchy").setAttribute("alt", ".");
979          break;
980        case CONTINUE_REGULAR:
981          img.setAttribute("src", srcFor(imagePath, "tbl_vjoin"+sfx+".png")).setAttribute("style", "background-color: inherit").setAttribute("class", "hierarchy").setAttribute("alt", ".");
982          break;
983        case CONTINUE_SLICER:
984          img.setAttribute("src", srcFor(imagePath, "tbl_vjoin_slicer"+sfx+".png")).setAttribute("style", "background-color: inherit").setAttribute("class", "hierarchy").setAttribute("alt", ".");
985          break;
986        case CONTINUE_SLICE:
987          img.setAttribute("src", srcFor(imagePath, "tbl_vjoin_slice"+sfx+".png")).setAttribute("style", "background-color: inherit").setAttribute("class", "hierarchy").setAttribute("alt", ".");
988          break;
989        default:
990          throw new Error("Unrecognized indent level: " + indents.get(indents.size()-1));
991        }
992        if (table.isActive() && hasChildren) {
993          img.setAttribute("onClick", "tableRowAction(this)");
994        }
995      }
996    }
997    else {
998      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 : "")+lineStyle);
999    }
1000    if (c.innerTable) {
1001      itc = itr.td();
1002    }
1003    if (!Utilities.noString(icon)) {
1004      XhtmlNode img = itc.addTag("img").setAttribute("alt", "icon").setAttribute("src", srcFor(imagePath, icon)).setAttribute("class", "hierarchy").setAttribute("style", "background-color: "+color+"; background-color: inherit").setAttribute("alt", ".");
1005      if (hint != null)
1006        img.setAttribute("title", hint);
1007      itc.addText(" ");
1008    }
1009    for (Piece p : c.pieces) {
1010      if (!Utilities.noString(p.getTag())) {
1011        XhtmlNode tag = itc.addTag(p.getTag());
1012        if (p.attributes != null)
1013          for (String n : p.attributes.keySet())
1014            tag.setAttribute(n, p.attributes.get(n));
1015        if (p.getHint() != null)
1016          tag.setAttribute("title", p.getHint());
1017        addStyle(tag, p);
1018        if (p.hasChildren()) {
1019          tag.addChildNodes(p.getChildren());
1020        }
1021      } else if (!Utilities.noString(p.getReference())) {
1022        XhtmlNode a = addStyle(itc.addTag("a"), p);
1023        a.setAttribute("href", prefixLocalHref(p.getReference()));
1024        if (mode == TableGenerationMode.XHTML && suppressExternals) {
1025          a.setAttribute("no-external", "true"); // deprecated - will be removed once everyone has dealt with the change
1026          a.setAttribute("data-no-external", "true");
1027        }
1028        if (!Utilities.noString(p.getHint()))
1029          a.setAttribute("title", p.getHint());
1030        if (p.getText() != null) {
1031          a.addText(p.getText());
1032        } else {
1033          a.addChildren(p.getChildren());
1034        }
1035        addStyle(a, p);
1036        if (p.getTagImg() != null) {
1037          a.tx(" ");
1038          a.img(p.getTagImg(), null);
1039        }
1040        
1041        if (p.hasChildren()) {
1042          itc.addChildNodes(p.getChildren());
1043        }
1044      } else { 
1045        if (!Utilities.noString(p.getHint())) {
1046          XhtmlNode s = addStyle(itc.addTag("span"), p);
1047          s.setAttribute("title", p.getHint());
1048          s.addText(p.getText());
1049        } else if (p.getStyle() != null) {
1050          XhtmlNode s = addStyle(itc.addTag("span"), p);
1051          s.addText(p.getText());
1052        } else {
1053          itc.addText(p.getText());
1054        }
1055        if (p.hasChildren()) {
1056          itc.addChildNodes(p.getChildren());
1057        }
1058        if (p.getTagImg() != null) {
1059          itc.tx(" ");
1060          itc.img(p.getTagImg(), null);
1061        }
1062      }
1063    }
1064    if (makeTargets && !Utilities.noString(anchor)) {
1065      tc.addTag("a").setAttribute("name", prefixAnchor(nmTokenize(anchor))).addText(" ");
1066    }
1067    return tc;
1068  }
1069
1070
1071  private XhtmlNode addStyle(XhtmlNode node, Piece p) {
1072    if (p.getStyle() != null)
1073      node.setAttribute("style", p.getStyle());
1074    return node;
1075  }
1076
1077  private String nmTokenize(String anchor) {
1078    return anchor.replace("[", "_").replace("]", "_");
1079  }
1080  
1081  private String srcFor(String corePrefix, String filename) throws IOException {
1082    if (!treelines && filename.startsWith("tbl")) {
1083      if (filename.contains("-open")) {
1084        filename = "tbl-open.png";
1085      } else if (filename.contains("-closed")) {
1086        filename = "tbl-closed.png";
1087      } else {
1088        filename = "tbl_blank.png";
1089      }
1090    }
1091    if (inLineGraphics) {
1092      if (files.containsKey(filename))
1093        return files.get(filename);
1094      StringBuilder b = new StringBuilder();
1095      b.append("data:image/png;base64,");
1096      byte[] bytes;
1097      File file = ManagedFileAccess.file(Utilities.path(dest, filename));
1098      if (!file.exists()) // because sometime this is called real early before the files exist. it will be built again later because of this
1099        bytes = new byte[0]; 
1100      else
1101        bytes = FileUtils.readFileToByteArray(file);
1102      b.append(new String(Base64.encodeBase64(bytes)));
1103      //      files.put(filename, b.toString());
1104      return b.toString();
1105    } else {
1106      return corePrefix+filename;
1107    }
1108  }
1109
1110  public static String help16AsData() throws IOException {
1111    ClassLoader classLoader = HierarchicalTableGenerator.class.getClassLoader();
1112    InputStream help = classLoader.getResourceAsStream("help16.png");
1113    StringBuilder b = new StringBuilder();
1114    b.append("data:image/png;base64,");
1115    byte[] bytes = FileUtilities.streamToBytes(help);
1116    b.append(new String(Base64.encodeBase64(bytes)));
1117    return b.toString();
1118  }
1119  
1120  private void checkModel(TableModel model) throws FHIRException  {
1121    check(!model.getTitles().isEmpty(), "Must have titles");
1122    int tc = 0;
1123    for (Cell c : model.getTitles()) {
1124      check(c);
1125      tc = tc + c.span;
1126    }
1127    int i = 0;
1128    for (Row r : model.getRows()) { 
1129      check(r, "rows", tc, "", i, model.getRows().size());
1130      i++;
1131    }
1132  }
1133
1134
1135  private void check(Cell c) throws FHIRException  {  
1136    boolean hasText = false;
1137    for (Piece p : c.pieces)
1138      if (!Utilities.noString(p.getText()))
1139        hasText = true;
1140    check(hasText, "Title cells must have text");    
1141  }
1142
1143
1144  private void check(Row r, String string, int size, String path, int index, int total) throws FHIRException  {
1145    String id = Integer.toString(index)+".";
1146    if (total <= 26) {
1147      char c = (char) ('a'+index);
1148      id = Character.toString(c);
1149    }
1150    path = path + id;
1151    r.setId(path);
1152    int tc = 0;
1153    for (Cell c : r.getCells()) {
1154      tc = tc + c.span;
1155    }
1156    if (tc != size) {
1157      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());      
1158    }
1159    int i = 0;
1160    for (Row c : r.getSubRows()) {
1161      check(c, "rows", size, path, i, r.getSubRows().size());
1162      i++;
1163    }
1164  }
1165
1166
1167  private String checkExists(List<Integer> indents, boolean hasChildren, int lineColor, Set<String> outputTracker) throws IOException  {
1168    String filename = makeName(indents);
1169    
1170    StringBuilder b = new StringBuilder();
1171    if (inLineGraphics) {
1172      if (files.containsKey(filename))
1173        return files.get(filename);
1174      ByteArrayOutputStream bytes = new ByteArrayOutputStream();
1175      genImage(indents, hasChildren, lineColor, bytes);
1176      b.append("data:image/png;base64,");
1177      byte[] encodeBase64 = Base64.encodeBase64(bytes.toByteArray());
1178      b.append(new String(encodeBase64));
1179      files.put(filename, b.toString());
1180      return b.toString();
1181    } else if (treelines) {
1182      b.append("tbl_bck");
1183      for (Integer i : indents)
1184        b.append(Integer.toString(i));
1185      int indent = lineColor*2 + (hasChildren?1:0);
1186      b.append(Integer.toString(indent));
1187      b.append(".png");
1188      String file = Utilities.path(dest, b.toString());
1189      if (!ManagedFileAccess.file(file).exists()) {
1190        File newFile = ManagedFileAccess.file(file);
1191        if (newFile.getParentFile() == null) {
1192          throw new Error("No source directory provided. ("+file+")");
1193        } else {
1194          newFile.getParentFile().mkdirs();
1195        }
1196        newFile.createNewFile();
1197        FileOutputStream stream = ManagedFileAccess.outStream(file);
1198        try {
1199          genImage(indents, hasChildren, lineColor, stream);
1200          if (outputTracker!=null)
1201            outputTracker.add(file);
1202        } finally {
1203          stream.close();
1204        }
1205      }
1206      return b.toString();
1207    } else {
1208      return "tbl_bck0.png";
1209    }
1210  }
1211
1212
1213  private void genImage(List<Integer> indents, boolean hasChildren, int lineColor, OutputStream stream) throws IOException {
1214    BufferedImage bi = new BufferedImage(800, 2, BufferedImage.TYPE_INT_ARGB);
1215    // i have no idea why this works to make these pixels transparent. It defies logic. 
1216    // But this combination of INT_ARGB and filling with grey magically worked when nothing else did. So it stays as is.
1217    Color grey = new Color(99,99,99,0); 
1218    for (int i = 0; i < 800; i++) {
1219      bi.setRGB(i, 0, grey.getRGB());
1220      bi.setRGB(i, 1, grey.getRGB());
1221    }
1222    Color black = new Color(0, 0, 0);
1223    Color green = new Color(14,209,69);
1224    Color gold = new Color(212,168,21);
1225    for (int i = 0; i < indents.size(); i++) {
1226      int indent = indents.get(i).intValue();
1227      if (indent == CONTINUE_REGULAR)
1228        bi.setRGB(12+(i*16), 0, black.getRGB());
1229      else if (indent == CONTINUE_SLICER)
1230        bi.setRGB(12+(i*16), 0, green.getRGB());
1231      else if (indent == CONTINUE_SLICE)
1232        bi.setRGB(12+(i*16), 0, gold.getRGB());
1233    }
1234    if (hasChildren) {
1235      if (lineColor==0)
1236        bi.setRGB(12+(indents.size()*16), 0, black.getRGB());
1237      else if (lineColor==1)
1238        bi.setRGB(12+(indents.size()*16), 0, green.getRGB());
1239      else if (lineColor==2)
1240        bi.setRGB(12+(indents.size()*16), 0, gold.getRGB());
1241    }
1242    ImageIO.write(bi, "PNG", stream);
1243  }
1244
1245  private String makeName(List<Integer> indents) {
1246    StringBuilder b = new StringBuilder();
1247    b.append("indents:");
1248    for (Integer i : indents)
1249      b.append(Integer.toString(i));
1250    return b.toString();
1251  }
1252
1253  private void check(boolean check, String message) throws FHIRException  {
1254    if (!check)
1255      throw new FHIRException(message);
1256  }
1257
1258  public void emptyRow(TableModel model, int cellCount) {
1259    Row r = new Row();
1260    model.rows.add(r);
1261    for (int i = 0; i < cellCount; i++) {
1262      r.getCells().add(new Cell());
1263    }
1264  }
1265  
1266
1267  public String getUniqueLocalPrefix() {
1268    return uniqueLocalPrefix;
1269  }
1270
1271  public void setUniqueLocalPrefix(String uniqueLocalPrefix) {
1272    if (Utilities.noString(uniqueLocalPrefix)) {
1273      throw new Error("what?");
1274    }
1275    this.uniqueLocalPrefix = uniqueLocalPrefix;
1276  }
1277
1278  public String prefixAnchor(String anchor) {
1279    return Utilities.noString(uniqueLocalPrefix) ? anchor : uniqueLocalPrefix+"-" + anchor;
1280  }
1281
1282  public String prefixLocalHref(String url) {
1283    if (url == null || Utilities.noString(uniqueLocalPrefix) || !url.startsWith("#")) {
1284      return url;
1285    }
1286    return "#"+uniqueLocalPrefix+"-"+url.substring(1);
1287  }
1288
1289  public boolean isTreelines() {
1290    return treelines;
1291  }
1292
1293  public void setTreelines(boolean treelines) {
1294    this.treelines = treelines;
1295  }
1296  
1297}