JAL-1641 fixed broken functionalities after refactor
[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
101       AlignmentExportData exportData = ap.alignFrame.getAlignmentForExport(
102               JSONFile.FILE_DESC, av);
103       if (exportData.getSettings().isCancelled())
104       {
105         return;
106       }
107       String 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 jsonData = JSONFile.getJSONData(ap);
114       String htmlData = getHtml(titleSvgData, alignSvgData, jsonData);
115
116       FileOutputStream out = new FileOutputStream(file);
117       out.write(htmlData.getBytes());
118       out.flush();
119       out.close();
120       if (!(System.getProperty("java.awt.headless") != null && System
121               .getProperty("java.awt.headless").equals("true")))
122       {
123       jalview.util.BrowserLauncher.openURL("file:///" + file);
124       }
125     } catch (Exception e)
126     {
127       e.printStackTrace();
128     }
129   }
130   
131   static JalviewFileChooser getHTMLChooser()
132   {
133     return new jalview.io.JalviewFileChooser(
134             jalview.bin.Cache.getProperty("LAST_DIRECTORY"), new String[]
135             { "html" }, new String[]
136             { "Hypertext Markup Language" }, "Hypertext Markup Language");
137   }
138
139   public int printUnwrapped(int pwidth, int pheight, int pi, Graphics... pg)
140           throws PrinterException
141   {
142     int idWidth = ap.getVisibleIdWidth(false);
143     FontMetrics fm = ap.getFontMetrics(av.getFont());
144     int scaleHeight = av.getCharHeight() + fm.getDescent();
145
146     pg[0].setColor(Color.white);
147     pg[0].fillRect(0, 0, pwidth, pheight);
148     pg[0].setFont(av.getFont());
149
150     // //////////////////////////////////
151     // / How many sequences and residues can we fit on a printable page?
152     int totalRes = (pwidth - idWidth) / av.getCharWidth();
153     int totalSeq = (pheight - scaleHeight) / av.getCharHeight() - 1;
154     int pagesWide = (av.getAlignment().getWidth() / totalRes) + 1;
155
156     // ///////////////////////////
157     // / Only print these sequences and residues on this page
158     int startRes;
159
160     // ///////////////////////////
161     // / Only print these sequences and residues on this page
162     int endRes;
163
164     // ///////////////////////////
165     // / Only print these sequences and residues on this page
166     int startSeq;
167
168     // ///////////////////////////
169     // / Only print these sequences and residues on this page
170     int endSeq;
171     startRes = (pi % pagesWide) * totalRes;
172     endRes = (startRes + totalRes) - 1;
173
174     if (endRes > (av.getAlignment().getWidth() - 1))
175     {
176       endRes = av.getAlignment().getWidth() - 1;
177     }
178     startSeq = (pi / pagesWide) * totalSeq;
179     endSeq = startSeq + totalSeq;
180     if (endSeq > av.getAlignment().getHeight())
181     {
182       endSeq = av.getAlignment().getHeight();
183     }
184     int pagesHigh = ((av.getAlignment().getHeight() / totalSeq) + 1)
185             * pheight;
186     if (av.isShowAnnotation())
187     {
188       pagesHigh += ap.getAnnotationPanel().adjustPanelHeight() + 3;
189     }
190     pagesHigh /= pheight;
191     if (pi >= (pagesWide * pagesHigh))
192     {
193       return Printable.NO_SUCH_PAGE;
194     }
195
196     // draw Scale
197     pg[1].translate(0, 0);
198     ap.getScalePanel().drawScale(pg[1], startRes, endRes, pwidth - idWidth,
199             scaleHeight);
200     pg[1].translate(-idWidth, scaleHeight);
201
202     // //////////////
203     // Draw the ids
204     Color currentColor = null;
205     Color currentTextColor = null;
206     pg[0].translate(0, scaleHeight);
207     pg[0].setFont(ap.getIdPanel().getIdCanvas().getIdfont());
208     SequenceI seq;
209     for (int i = startSeq; i < endSeq; i++)
210     {
211       seq = av.getAlignment().getSequenceAt(i);
212       if ((av.getSelectionGroup() != null)
213               && av.getSelectionGroup().getSequences(null).contains(seq))
214       {
215         currentColor = Color.gray;
216         currentTextColor = Color.black;
217       }
218       else
219       {
220         currentColor = av.getSequenceColour(seq);
221         currentTextColor = Color.black;
222       }
223       pg[0].setColor(currentColor);
224       pg[0].fillRect(0, (i - startSeq) * av.getCharHeight(), idWidth,
225               av.getCharHeight());
226       pg[0].setColor(currentTextColor);
227       int xPos = 0;
228       if (av.isRightAlignIds())
229       {
230         fm = pg[0].getFontMetrics();
231         xPos = idWidth
232                 - fm.stringWidth(seq.getDisplayId(av.getShowJVSuffix()))
233                 - 4;
234       }
235       pg[0].drawString(
236               seq.getDisplayId(av.getShowJVSuffix()),
237               xPos,
238               (((i - startSeq) * av.getCharHeight()) + av.getCharHeight())
239                       - (av.getCharHeight() / 5));
240     }
241     pg[0].setFont(av.getFont());
242     pg[0].translate(idWidth, 0);
243
244     // draw main sequence panel
245     pg[1].translate(idWidth, 0);
246     ap.getSeqPanel().seqCanvas.drawPanel(pg[1], startRes, endRes, startSeq,
247             endSeq, 0);
248     if (av.isShowAnnotation() && (endSeq == av.getAlignment().getHeight()))
249     {
250       // draw annotation label - need to offset for current scroll position
251       int offset = -ap.getAlabels().getScrollOffset();
252       pg[0].translate(0, offset);
253       pg[0].translate(-idWidth - 3,
254               (endSeq - startSeq) * av.getCharHeight() + 3);
255       ap.getAlabels().drawComponent(pg[0], idWidth);
256       pg[0].translate(idWidth + 3, 0);
257       pg[0].translate(0, -offset);
258
259       // draw annotation - need to offset for current scroll position
260       pg[1].translate(0, offset);
261       pg[1].translate(-idWidth - 3,
262               (endSeq - startSeq) * av.getCharHeight() + 3);
263       pg[1].translate(idWidth + 3, 0);
264       ap.getAnnotationPanel().renderer.drawComponent(
265               ap.getAnnotationPanel(), av, pg[1], -1, startRes, endRes + 1);
266       pg[1].translate(0, -offset);
267     }
268
269     return Printable.PAGE_EXISTS;
270   }
271   
272   private String getHtml(String titleSvg, String alignmentSvg,
273           String jsonData)
274   {
275     StringBuilder htmlSvg = new StringBuilder();
276     htmlSvg.append("<html>\n");
277     if (jsonData != null)
278     {
279       htmlSvg.append("<input type=\"hidden\" name=\"seqData\" id=\"seqData\" value='"
280               + jsonData + "'>");
281     }
282     htmlSvg.append("\n<style type=\"text/css\"> "
283             + "div.parent{ width:100%;<!-- overflow: auto; -->}\n"
284             + "div.titlex{ width:11%; float: left; }\n"
285             + "div.align{ width:89%; float: right; }\n"
286             + ".sub-category-container {overflow-y: scroll; overflow-x: hidden; width: 100%; height: 100%;}\n"
287             + "object {pointer-events: none;}"
288             + "</style>");
289     htmlSvg.append("<div>");
290     htmlSvg.append(
291 "<div class=\"titlex\">");
292     htmlSvg.append(
293 "<div class=\"sub-category-container\"> ")
294             .append(titleSvg)
295             .append("</div>")
296             .append("</div>\n\n<!-- ========================================================================================== -->\n\n");
297     htmlSvg.append(
298 "<div class=\"align\" >");
299     htmlSvg.append(
300             "<div class=\"sub-category-container\"> <div style=\"overflow-x: scroll;\">")
301             .append(alignmentSvg)
302 .append("</div></div>")
303             .append("</div>");
304     htmlSvg.append("</div>");
305
306     htmlSvg.append("<script language=\"JavaScript\" type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js\"></script>\n"
307             + "<script language=\"JavaScript\" type=\"text/javascript\"  src=\"//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js\"></script>\n"
308             + "<script>\n"
309             + "var subCatContainer = $(\".sub-category-container\");\n"
310             + "subCatContainer.scroll(\nfunction() {\n"
311             + "subCatContainer.scrollTop($(this).scrollTop());\n});\n");
312
313     htmlSvg.append("</script></hmtl>");
314
315     return htmlSvg.toString();
316   }
317 }