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