JAL-1835 made BioJSON embedding to html exports configurable, and trapped import...
[jalview.git] / src / jalview / io / HtmlSvgOutput.java
1 package jalview.io;
2
3 import jalview.api.FeatureRenderer;
4 import jalview.datamodel.AlignmentExportData;
5 import jalview.datamodel.SequenceI;
6 import jalview.gui.AlignViewport;
7 import jalview.gui.AlignmentPanel;
8 import jalview.gui.HTMLOptions;
9 import jalview.math.AlignmentDimension;
10 import jalview.util.MessageManager;
11
12 import java.awt.Color;
13 import java.awt.FontMetrics;
14 import java.awt.Graphics;
15 import java.awt.print.Printable;
16 import java.awt.print.PrinterException;
17 import java.io.File;
18 import java.io.FileOutputStream;
19
20 import org.jfree.graphics2d.svg.SVGGraphics2D;
21 import org.jfree.graphics2d.svg.SVGHints;
22
23 public class HtmlSvgOutput
24 {
25   AlignViewport av;
26
27   FeatureRenderer fr;
28   AlignmentPanel ap;
29
30
31   public HtmlSvgOutput(File file, AlignmentPanel ap)
32   {
33     this.av = ap.av;
34     this.ap = ap;
35     fr = ap.cloneFeatureRenderer();
36     generateHtmlSvgOutput(file);
37   }
38
39   public void generateHtmlSvgOutput(File file)
40   {
41     try
42     {
43       if (file == null /*
44                         * && !(System.getProperty("java.awt.headless") != null
45                         * && System
46                         * .getProperty("java.awt.headless").equals("true"))
47                         */)
48       {
49
50       JalviewFileChooser chooser = getHTMLChooser();
51       chooser.setFileView(new jalview.io.JalviewFileView());
52       chooser.setDialogTitle(ap.alignFrame.getTitle());
53       chooser.setToolTipText(MessageManager.getString("action.save"));
54       int value = chooser.showSaveDialog(ap.alignFrame);
55
56       if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
57       {
58         jalview.bin.Cache.setProperty("LAST_DIRECTORY", chooser
59                 .getSelectedFile().getParent());
60         file = chooser.getSelectedFile();
61       }
62       }
63
64       AlignmentDimension aDimension = ap.getAlignmentDimension();
65       SVGGraphics2D g1 = new SVGGraphics2D(aDimension.getWidth(),
66               aDimension.getHeight());
67       SVGGraphics2D g2 = new SVGGraphics2D(aDimension.getWidth(),
68               aDimension.getHeight());
69
70       String renderStyle = jalview.bin.Cache.getDefault("HTML_RENDERING",
71               "Prompt each time");
72
73       // If we need to prompt, and if the GUI is visible then
74       // Prompt for rendering style
75       if (renderStyle.equalsIgnoreCase("Prompt each time")
76               && !(System.getProperty("java.awt.headless") != null && System
77                       .getProperty("java.awt.headless").equals("true")))
78       {
79         HTMLOptions svgOption = new HTMLOptions();
80         renderStyle = svgOption.getValue();
81
82         if (renderStyle == null || svgOption.cancelled)
83         {
84           return;
85         }
86       }
87
88       if (renderStyle.equalsIgnoreCase("lineart"))
89       {
90         g1.setRenderingHint(SVGHints.KEY_DRAW_STRING_TYPE,
91                 SVGHints.VALUE_DRAW_STRING_TYPE_VECTOR);
92         g2.setRenderingHint(SVGHints.KEY_DRAW_STRING_TYPE,
93                 SVGHints.VALUE_DRAW_STRING_TYPE_VECTOR);
94       }
95       printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0, g1,
96               g2);
97
98       String titleSvgData = g1.getSVGDocument();
99       String alignSvgData = g2.getSVGDocument();
100       String jsonData = null;
101       boolean isEmbbedBioJSON = Boolean.valueOf(jalview.bin.Cache
102               .getDefault("EXPORT_EMBBED_BIOJSON", "true"));
103       if (isEmbbedBioJSON)
104       {
105       AlignmentExportData exportData = ap.alignFrame.getAlignmentForExport(
106               JSONFile.FILE_DESC, av);
107       if (exportData.getSettings().isCancelled())
108       {
109         return;
110       }
111         jsonData = new FormatAdapter(ap, exportData.getSettings())
112               .formatSequences(JSONFile.FILE_DESC, exportData
113                       .getAlignment(), exportData.getOmitHidden(),
114                       exportData.getStartEndPostions(), ap
115                               .getAlignViewport().getColumnSelection());
116       }
117       String htmlData = getHtml(titleSvgData, alignSvgData, jsonData);
118       FileOutputStream out = new FileOutputStream(file);
119       out.write(htmlData.getBytes());
120       out.flush();
121       out.close();
122       if (!(System.getProperty("java.awt.headless") != null && System
123               .getProperty("java.awt.headless").equals("true")))
124       {
125       jalview.util.BrowserLauncher.openURL("file:///" + file);
126       }
127     } catch (Exception e)
128     {
129       e.printStackTrace();
130     }
131   }
132   
133   static JalviewFileChooser getHTMLChooser()
134   {
135     return new jalview.io.JalviewFileChooser(
136             jalview.bin.Cache.getProperty("LAST_DIRECTORY"), new String[]
137             { "html" }, new String[]
138             { "Hypertext Markup Language" }, "Hypertext Markup Language");
139   }
140
141   public int printUnwrapped(int pwidth, int pheight, int pi, Graphics... pg)
142           throws PrinterException
143   {
144     int idWidth = ap.getVisibleIdWidth(false);
145     FontMetrics fm = ap.getFontMetrics(av.getFont());
146     int scaleHeight = av.getCharHeight() + fm.getDescent();
147
148     pg[0].setColor(Color.white);
149     pg[0].fillRect(0, 0, pwidth, pheight);
150     pg[0].setFont(av.getFont());
151
152     // //////////////////////////////////
153     // / How many sequences and residues can we fit on a printable page?
154     int totalRes = (pwidth - idWidth) / av.getCharWidth();
155     int totalSeq = (pheight - scaleHeight) / av.getCharHeight() - 1;
156     int pagesWide = (av.getAlignment().getWidth() / totalRes) + 1;
157
158     // ///////////////////////////
159     // / Only print these sequences and residues on this page
160     int startRes;
161
162     // ///////////////////////////
163     // / Only print these sequences and residues on this page
164     int endRes;
165
166     // ///////////////////////////
167     // / Only print these sequences and residues on this page
168     int startSeq;
169
170     // ///////////////////////////
171     // / Only print these sequences and residues on this page
172     int endSeq;
173     startRes = (pi % pagesWide) * totalRes;
174     endRes = (startRes + totalRes) - 1;
175
176     if (endRes > (av.getAlignment().getWidth() - 1))
177     {
178       endRes = av.getAlignment().getWidth() - 1;
179     }
180     startSeq = (pi / pagesWide) * totalSeq;
181     endSeq = startSeq + totalSeq;
182     if (endSeq > av.getAlignment().getHeight())
183     {
184       endSeq = av.getAlignment().getHeight();
185     }
186     int pagesHigh = ((av.getAlignment().getHeight() / totalSeq) + 1)
187             * pheight;
188     if (av.isShowAnnotation())
189     {
190       pagesHigh += ap.getAnnotationPanel().adjustPanelHeight() + 3;
191     }
192     pagesHigh /= pheight;
193     if (pi >= (pagesWide * pagesHigh))
194     {
195       return Printable.NO_SUCH_PAGE;
196     }
197
198     // draw Scale
199     pg[1].translate(0, 0);
200     ap.getScalePanel().drawScale(pg[1], startRes, endRes, pwidth - idWidth,
201             scaleHeight);
202     pg[1].translate(-idWidth, scaleHeight);
203
204     // //////////////
205     // Draw the ids
206     Color currentColor = null;
207     Color currentTextColor = null;
208     pg[0].translate(0, scaleHeight);
209     pg[0].setFont(ap.getIdPanel().getIdCanvas().getIdfont());
210     SequenceI seq;
211     for (int i = startSeq; i < endSeq; i++)
212     {
213       seq = av.getAlignment().getSequenceAt(i);
214       if ((av.getSelectionGroup() != null)
215               && av.getSelectionGroup().getSequences(null).contains(seq))
216       {
217         currentColor = Color.gray;
218         currentTextColor = Color.black;
219       }
220       else
221       {
222         currentColor = av.getSequenceColour(seq);
223         currentTextColor = Color.black;
224       }
225       pg[0].setColor(currentColor);
226       pg[0].fillRect(0, (i - startSeq) * av.getCharHeight(), idWidth,
227               av.getCharHeight());
228       pg[0].setColor(currentTextColor);
229       int xPos = 0;
230       if (av.isRightAlignIds())
231       {
232         fm = pg[0].getFontMetrics();
233         xPos = idWidth
234                 - fm.stringWidth(seq.getDisplayId(av.getShowJVSuffix()))
235                 - 4;
236       }
237       pg[0].drawString(
238               seq.getDisplayId(av.getShowJVSuffix()),
239               xPos,
240               (((i - startSeq) * av.getCharHeight()) + av.getCharHeight())
241                       - (av.getCharHeight() / 5));
242     }
243     pg[0].setFont(av.getFont());
244     pg[0].translate(idWidth, 0);
245
246     // draw main sequence panel
247     pg[1].translate(idWidth, 0);
248     ap.getSeqPanel().seqCanvas.drawPanel(pg[1], startRes, endRes, startSeq,
249             endSeq, 0);
250     if (av.isShowAnnotation() && (endSeq == av.getAlignment().getHeight()))
251     {
252       // draw annotation label - need to offset for current scroll position
253       int offset = -ap.getAlabels().getScrollOffset();
254       pg[0].translate(0, offset);
255       pg[0].translate(-idWidth - 3,
256               (endSeq - startSeq) * av.getCharHeight() + 3);
257       ap.getAlabels().drawComponent(pg[0], idWidth);
258       pg[0].translate(idWidth + 3, 0);
259       pg[0].translate(0, -offset);
260
261       // draw annotation - need to offset for current scroll position
262       pg[1].translate(0, offset);
263       pg[1].translate(-idWidth - 3,
264               (endSeq - startSeq) * av.getCharHeight() + 3);
265       pg[1].translate(idWidth + 3, 0);
266       ap.getAnnotationPanel().renderer.drawComponent(
267               ap.getAnnotationPanel(), av, pg[1], -1, startRes, endRes + 1);
268       pg[1].translate(0, -offset);
269     }
270
271     return Printable.PAGE_EXISTS;
272   }
273   
274   private String getHtml(String titleSvg, String alignmentSvg,
275           String jsonData)
276   {
277     StringBuilder htmlSvg = new StringBuilder();
278     htmlSvg.append("<html>\n");
279     if (jsonData != null)
280     {
281       htmlSvg.append("<button onclick=\"javascipt:openJalviewUsingCurrentUrl();\">Launch in Jalview</button>");
282       htmlSvg.append("<input type=\"hidden\" name=\"seqData\" id=\"seqData\" value='"
283               + jsonData + "'>");
284     }
285     htmlSvg.append("\n<style type=\"text/css\"> "
286             + "div.parent{ width:100%;<!-- overflow: auto; -->}\n"
287             + "div.titlex{ width:11%; float: left; }\n"
288             + "div.align{ width:89%; float: right; }\n"
289             + ".sub-category-container {overflow-y: scroll; overflow-x: hidden; width: 100%; height: 100%;}\n"
290             + "object {pointer-events: none;}"
291             + "</style>");
292     htmlSvg.append("<div>");
293     htmlSvg.append(
294 "<div class=\"titlex\">");
295     htmlSvg.append(
296 "<div class=\"sub-category-container\"> ")
297             .append(titleSvg)
298             .append("</div>")
299             .append("</div>\n\n<!-- ========================================================================================== -->\n\n");
300     htmlSvg.append(
301 "<div class=\"align\" >");
302     htmlSvg.append(
303             "<div class=\"sub-category-container\"> <div style=\"overflow-x: scroll;\">")
304             .append(alignmentSvg)
305 .append("</div></div>")
306             .append("</div>");
307     htmlSvg.append("</div>");
308
309     htmlSvg.append("<script language=\"JavaScript\" type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js\"></script>\n"
310             + "<script language=\"JavaScript\" type=\"text/javascript\"  src=\"//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js\"></script>\n"
311             + "<script>\n"
312             + "var subCatContainer = $(\".sub-category-container\");\n"
313             + "subCatContainer.scroll(\nfunction() {\n"
314             + "subCatContainer.scrollTop($(this).scrollTop());\n});\n");
315
316     htmlSvg.append("</script>\n");
317
318     // javascript for launching file in Jalview
319
320     htmlSvg.append("<script language=\"JavaScript\">\n");
321     htmlSvg.append("function openJalviewUsingCurrentUrl(){\n");
322     htmlSvg.append("    var json = JSON.parse(document.getElementById(\"seqData\").value);\n");
323     htmlSvg.append("    var jalviewVersion = json['appSettings'].version;\n");
324     htmlSvg.append("    var url = json['appSettings'].webStartUrl;\n");
325     htmlSvg.append("    var myForm = document.createElement(\"form\");\n\n");
326     htmlSvg.append("    var heap = document.createElement(\"input\");\n");
327     htmlSvg.append("    heap.setAttribute(\"name\", \"jvm-max-heap\") ;\n");
328     htmlSvg.append("    heap.setAttribute(\"value\", \"2G\");\n\n");
329     htmlSvg.append("    var target = document.createElement(\"input\");\n");
330     htmlSvg.append("    target.setAttribute(\"name\", \"open\");\n");
331     htmlSvg.append("    target.setAttribute(\"value\", document.URL);\n\n");
332     htmlSvg.append("    var jvVersion = document.createElement(\"input\");\n");
333     htmlSvg.append("    jvVersion.setAttribute(\"name\", \"version\") ;\n");
334     htmlSvg.append("    jvVersion.setAttribute(\"value\", jalviewVersion);\n\n");
335     htmlSvg.append("    myForm.action = url;\n");
336     htmlSvg.append("    myForm.appendChild(heap);\n");
337     htmlSvg.append("    myForm.appendChild(target);\n");
338     htmlSvg.append("    myForm.appendChild(jvVersion);\n");
339     htmlSvg.append("    document.body.appendChild(myForm);\n");
340     htmlSvg.append("    myForm.submit() ;\n");
341     htmlSvg.append("    document.body.removeChild(myForm);\n");
342     htmlSvg.append("}\n");
343     htmlSvg.append("</script>\n");
344     htmlSvg.append("</hmtl>");
345     return htmlSvg.toString();
346   }
347 }