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