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