JAL-1976 catch and handle OOM Error
[jalview.git] / src / jalview / io / HtmlSvgOutput.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.io;
22
23 import jalview.api.AlignExportSettingI;
24 import jalview.api.FeatureRenderer;
25 import jalview.datamodel.AlignmentExportData;
26 import jalview.datamodel.SequenceI;
27 import jalview.gui.AlignViewport;
28 import jalview.gui.AlignmentPanel;
29 import jalview.gui.HTMLOptions;
30 import jalview.gui.IProgressIndicator;
31 import jalview.gui.OOMWarning;
32 import jalview.math.AlignmentDimension;
33 import jalview.util.MessageManager;
34
35 import java.awt.Color;
36 import java.awt.FontMetrics;
37 import java.awt.Graphics;
38 import java.awt.print.Printable;
39 import java.awt.print.PrinterException;
40 import java.io.File;
41 import java.io.FileOutputStream;
42
43 import org.jfree.graphics2d.svg.SVGGraphics2D;
44 import org.jfree.graphics2d.svg.SVGHints;
45
46 public class HtmlSvgOutput
47 {
48   AlignViewport av;
49
50   FeatureRenderer fr;
51
52   AlignmentPanel ap;
53
54   public HtmlSvgOutput(File file, AlignmentPanel ap)
55   {
56     this.av = ap.av;
57     this.ap = ap;
58     fr = ap.cloneFeatureRenderer();
59     generateHtmlSvgOutput(file);
60   }
61
62   public void generateHtmlSvgOutput(File file)
63   {
64     IProgressIndicator pIndicator = ap.alignFrame;
65     long pSessionId = System.currentTimeMillis();
66     try
67     {
68       boolean headless = (System.getProperty("java.awt.headless") != null && System
69               .getProperty("java.awt.headless").equals("true"));
70       if (file == null)
71       {
72         if (pIndicator != null && !headless)
73         {
74           pIndicator.setProgressBar(MessageManager.formatMessage(
75                   "status.waiting_for_user_to_select_output_file", "HTML"),
76                   pSessionId);
77         }
78         JalviewFileChooser chooser = getHTMLChooser();
79         chooser.setFileView(new jalview.io.JalviewFileView());
80         chooser.setDialogTitle(ap.alignFrame.getTitle());
81         chooser.setToolTipText(MessageManager.getString("action.save"));
82         int value = chooser.showSaveDialog(ap.alignFrame);
83
84         if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
85         {
86           jalview.bin.Cache.setProperty("LAST_DIRECTORY", chooser
87                   .getSelectedFile().getParent());
88           file = chooser.getSelectedFile();
89         }
90         else
91         {
92
93           if (pIndicator != null && !headless)
94         {
95             pIndicator.setProgressBar(MessageManager.formatMessage(
96                     "status.cancelled_image_export_operation", "HTML"),
97                     pSessionId);
98           }
99           return;
100         }
101       }
102
103       AlignmentDimension aDimension = ap.getAlignmentDimension();
104       SVGGraphics2D g1 = new SVGGraphics2D(aDimension.getWidth(),
105               aDimension.getHeight());
106       SVGGraphics2D g2 = new SVGGraphics2D(aDimension.getWidth(),
107               aDimension.getHeight());
108
109       String renderStyle = jalview.bin.Cache.getDefault("HTML_RENDERING",
110               "Prompt each time");
111
112       // If we need to prompt, and if the GUI is visible then
113       // Prompt for rendering style
114       if (renderStyle.equalsIgnoreCase("Prompt each time")
115               && !(System.getProperty("java.awt.headless") != null && System
116                       .getProperty("java.awt.headless").equals("true")))
117       {
118         HTMLOptions svgOption = new HTMLOptions();
119         renderStyle = svgOption.getValue();
120
121         if (renderStyle == null || svgOption.cancelled)
122         {
123           return;
124         }
125       }
126
127       if (renderStyle.equalsIgnoreCase("lineart"))
128       {
129         g1.setRenderingHint(SVGHints.KEY_DRAW_STRING_TYPE,
130                 SVGHints.VALUE_DRAW_STRING_TYPE_VECTOR);
131         g2.setRenderingHint(SVGHints.KEY_DRAW_STRING_TYPE,
132                 SVGHints.VALUE_DRAW_STRING_TYPE_VECTOR);
133       }
134       printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0, g1,
135               g2);
136
137       String titleSvgData = g1.getSVGDocument();
138       String alignSvgData = g2.getSVGDocument();
139       String jsonData = null;
140       boolean isEmbbedBioJSON = Boolean.valueOf(jalview.bin.Cache
141               .getDefault("EXPORT_EMBBED_BIOJSON", "true"));
142       if (isEmbbedBioJSON)
143       {
144         AlignExportSettingI exportSettings = new AlignExportSettingI()
145         {
146           @Override
147           public boolean isExportHiddenSequences()
148           {
149             return true;
150           }
151
152           @Override
153           public boolean isExportHiddenColumns()
154           {
155             return true;
156           }
157
158           @Override
159           public boolean isExportAnnotations()
160           {
161             return true;
162           }
163
164           @Override
165           public boolean isExportFeatures()
166           {
167             return true;
168           }
169
170           @Override
171           public boolean isExportGroups()
172           {
173             return true;
174           }
175
176           @Override
177           public boolean isCancelled()
178           {
179             return false;
180           }
181
182         };
183         AlignmentExportData exportData = jalview.gui.AlignFrame
184                 .getAlignmentForExport(JSONFile.FILE_DESC, av,
185                         exportSettings);
186         jsonData = new FormatAdapter(ap, exportData.getSettings())
187                 .formatSequences(JSONFile.FILE_DESC,
188                         exportData.getAlignment(),
189                         exportData.getOmitHidden(),
190                         exportData.getStartEndPostions(),
191                         av.getColumnSelection());
192       }
193       String htmlData = getHtml(titleSvgData, alignSvgData, jsonData);
194       FileOutputStream out = new FileOutputStream(file);
195       out.write(htmlData.getBytes());
196       out.flush();
197       out.close();
198       if (!(System.getProperty("java.awt.headless") != null && System
199               .getProperty("java.awt.headless").equals("true")))
200       {
201         jalview.util.BrowserLauncher.openURL("file:///" + file);
202       }
203       if (pIndicator != null && !headless)
204       {
205         pIndicator.setProgressBar(MessageManager.formatMessage(
206                 "status.export_complete", "HTML"), pSessionId);
207       }
208     } catch (OutOfMemoryError err)
209     {
210       System.out.println("########################\n" + "OUT OF MEMORY "
211               + file + "\n" + "########################");
212       new OOMWarning("Creating Image for " + file, err);
213     } catch (Exception e)
214     {
215       e.printStackTrace();
216       pIndicator.setProgressBar(MessageManager.formatMessage(
217               "info.error_creating_file", "HTML"), pSessionId);
218     }
219   }
220
221   static JalviewFileChooser getHTMLChooser()
222   {
223     return new jalview.io.JalviewFileChooser(
224             jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
225             new String[] { "html" },
226             new String[] { "Hypertext Markup Language" },
227             "Hypertext Markup Language");
228   }
229
230   public int printUnwrapped(int pwidth, int pheight, int pi, Graphics... pg)
231           throws PrinterException
232   {
233     int idWidth = ap.getVisibleIdWidth(false);
234     FontMetrics fm = ap.getFontMetrics(av.getFont());
235     int scaleHeight = av.getCharHeight() + fm.getDescent();
236
237     pg[0].setColor(Color.white);
238     pg[0].fillRect(0, 0, pwidth, pheight);
239     pg[0].setFont(av.getFont());
240
241     // //////////////////////////////////
242     // / How many sequences and residues can we fit on a printable page?
243     int totalRes = (pwidth - idWidth) / av.getCharWidth();
244     int totalSeq = (pheight - scaleHeight) / av.getCharHeight() - 1;
245     int pagesWide = (av.getAlignment().getWidth() / totalRes) + 1;
246
247     // ///////////////////////////
248     // / Only print these sequences and residues on this page
249     int startRes;
250
251     // ///////////////////////////
252     // / Only print these sequences and residues on this page
253     int endRes;
254
255     // ///////////////////////////
256     // / Only print these sequences and residues on this page
257     int startSeq;
258
259     // ///////////////////////////
260     // / Only print these sequences and residues on this page
261     int endSeq;
262     startRes = (pi % pagesWide) * totalRes;
263     endRes = (startRes + totalRes) - 1;
264
265     if (endRes > (av.getAlignment().getWidth() - 1))
266     {
267       endRes = av.getAlignment().getWidth() - 1;
268     }
269     startSeq = (pi / pagesWide) * totalSeq;
270     endSeq = startSeq + totalSeq;
271     if (endSeq > av.getAlignment().getHeight())
272     {
273       endSeq = av.getAlignment().getHeight();
274     }
275     int pagesHigh = ((av.getAlignment().getHeight() / totalSeq) + 1)
276             * pheight;
277     if (av.isShowAnnotation())
278     {
279       pagesHigh += ap.getAnnotationPanel().adjustPanelHeight() + 3;
280     }
281     pagesHigh /= pheight;
282     if (pi >= (pagesWide * pagesHigh))
283     {
284       return Printable.NO_SUCH_PAGE;
285     }
286
287     // draw Scale
288     pg[1].translate(0, 0);
289     ap.getScalePanel().drawScale(pg[1], startRes, endRes, pwidth - idWidth,
290             scaleHeight);
291     pg[1].translate(-idWidth, scaleHeight);
292
293     // //////////////
294     // Draw the ids
295     Color currentColor = null;
296     Color currentTextColor = null;
297     pg[0].translate(0, scaleHeight);
298     pg[0].setFont(ap.getIdPanel().getIdCanvas().getIdfont());
299     SequenceI seq;
300     for (int i = startSeq; i < endSeq; i++)
301     {
302       seq = av.getAlignment().getSequenceAt(i);
303       if ((av.getSelectionGroup() != null)
304               && av.getSelectionGroup().getSequences(null).contains(seq))
305       {
306         currentColor = Color.gray;
307         currentTextColor = Color.black;
308       }
309       else
310       {
311         currentColor = av.getSequenceColour(seq);
312         currentTextColor = Color.black;
313       }
314       pg[0].setColor(currentColor);
315       pg[0].fillRect(0, (i - startSeq) * av.getCharHeight(), idWidth,
316               av.getCharHeight());
317       pg[0].setColor(currentTextColor);
318       int xPos = 0;
319       if (av.isRightAlignIds())
320       {
321         fm = pg[0].getFontMetrics();
322         xPos = idWidth
323                 - fm.stringWidth(seq.getDisplayId(av.getShowJVSuffix()))
324                 - 4;
325       }
326       pg[0].drawString(seq.getDisplayId(av.getShowJVSuffix()), xPos,
327               (((i - startSeq) * av.getCharHeight()) + av.getCharHeight())
328                       - (av.getCharHeight() / 5));
329     }
330     pg[0].setFont(av.getFont());
331     pg[0].translate(idWidth, 0);
332
333     // draw main sequence panel
334     pg[1].translate(idWidth, 0);
335     ap.getSeqPanel().seqCanvas.drawPanel(pg[1], startRes, endRes, startSeq,
336             endSeq, 0);
337     if (av.isShowAnnotation() && (endSeq == av.getAlignment().getHeight()))
338     {
339       // draw annotation label - need to offset for current scroll position
340       int offset = -ap.getAlabels().getScrollOffset();
341       pg[0].translate(0, offset);
342       pg[0].translate(-idWidth - 3,
343               (endSeq - startSeq) * av.getCharHeight() + 3);
344       ap.getAlabels().drawComponent(pg[0], idWidth);
345       pg[0].translate(idWidth + 3, 0);
346       pg[0].translate(0, -offset);
347
348       // draw annotation - need to offset for current scroll position
349       pg[1].translate(0, offset);
350       pg[1].translate(-idWidth - 3,
351               (endSeq - startSeq) * av.getCharHeight() + 3);
352       pg[1].translate(idWidth + 3, 0);
353       ap.getAnnotationPanel().renderer.drawComponent(
354               ap.getAnnotationPanel(), av, pg[1], -1, startRes, endRes + 1);
355       pg[1].translate(0, -offset);
356     }
357
358     return Printable.PAGE_EXISTS;
359   }
360
361   private String getHtml(String titleSvg, String alignmentSvg,
362           String jsonData)
363   {
364     StringBuilder htmlSvg = new StringBuilder();
365     htmlSvg.append("<html>\n");
366     if (jsonData != null)
367     {
368       htmlSvg.append("<button onclick=\"javascipt:openJalviewUsingCurrentUrl();\">Launch in Jalview</button> &nbsp;");
369       htmlSvg.append("<input type=\"submit\" value=\"View raw BioJSON Data\" onclick=\"jQuery.facebox({ div:'#seqData' }); return false;\" />");
370       htmlSvg.append("<div style=\"display: none;\" name=\"seqData\" id=\"seqData\" >"
371               + jsonData + "</div>");
372       htmlSvg.append("<br/>&nbsp;");
373     }
374     htmlSvg.append("\n<style type=\"text/css\"> "
375             + "div.parent{ width:100%;<!-- overflow: auto; -->}\n"
376             + "div.titlex{ width:11%; float: left; }\n"
377             + "div.align{ width:89%; float: right; }\n"
378             + "div.main-container{ border: 2px solid blue; border: 2px solid blue; width: 99%;   min-height: 99%; }\n"
379             + ".sub-category-container {overflow-y: scroll; overflow-x: hidden; width: 100%; height: 100%;}\n"
380             + "object {pointer-events: none;}");
381     if (jsonData != null)
382     {
383       // facebox style sheet for displaying raw BioJSON data
384       htmlSvg.append("#facebox { position: absolute;  top: 0;   left: 0; z-index: 100; text-align: left; }\n"
385               + "#facebox .popup{ position:relative; border:3px solid rgba(0,0,0,0); -webkit-border-radius:5px;"
386               + "-moz-border-radius:5px; border-radius:5px; -webkit-box-shadow:0 0 18px rgba(0,0,0,0.4); -moz-box-shadow:0 0 18px rgba(0,0,0,0.4);"
387               + "box-shadow:0 0 18px rgba(0,0,0,0.4); }\n"
388               + "#facebox .content { display:table; width: 98%; padding: 10px; background: #fff; -webkit-border-radius:4px; -moz-border-radius:4px;"
389               + " border-radius:4px; }\n"
390               + "#facebox .content > p:first-child{ margin-top:0; }\n"
391               + "#facebox .content > p:last-child{ margin-bottom:0; }\n"
392               + "#facebox .close{ position:absolute; top:5px; right:5px; padding:2px; background:#fff; }\n"
393               + "#facebox .close img{ opacity:0.3; }\n"
394               + "#facebox .close:hover img{ opacity:1.0; }\n"
395               + "#facebox .loading { text-align: center; }\n"
396               + "#facebox .image { text-align: center;}\n"
397               + "#facebox img { border: 0;  margin: 0; }\n"
398               + "#facebox_overlay { position: fixed; top: 0px; left: 0px; height:100%; width:100%; }\n"
399               + ".facebox_hide { z-index:-100; }\n"
400               + ".facebox_overlayBG { background-color: #000;  z-index: 99;  }");
401     }
402
403     htmlSvg.append("</style>");
404     htmlSvg.append("<div class=\"main-container\" \n>");
405     htmlSvg.append("<div class=\"titlex\">\n");
406     htmlSvg.append("<div class=\"sub-category-container\"> \n");
407     htmlSvg.append(titleSvg);
408     htmlSvg.append("</div>");
409     htmlSvg.append("</div>\n\n<!-- ========================================================================================== -->\n\n");
410     htmlSvg.append("<div class=\"align\" >");
411     htmlSvg.append(
412             "<div class=\"sub-category-container\"> <div style=\"overflow-x: scroll;\">")
413             .append(alignmentSvg).append("</div></div>").append("</div>");
414     htmlSvg.append("</div>");
415
416     htmlSvg.append("<script language=\"JavaScript\" type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js\"></script>\n"
417             + "<script language=\"JavaScript\" type=\"text/javascript\"  src=\"http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js\"></script>\n"
418             + "<script>\n"
419             + "var subCatContainer = $(\".sub-category-container\");\n"
420             + "subCatContainer.scroll(\nfunction() {\n"
421             + "subCatContainer.scrollTop($(this).scrollTop());\n});\n");
422
423     htmlSvg.append("</script>\n");
424
425     // javascript for launching file in Jalview
426
427     htmlSvg.append("<script language=\"JavaScript\">\n");
428     htmlSvg.append("function openJalviewUsingCurrentUrl(){\n");
429     htmlSvg.append("    var json = JSON.parse(document.getElementById(\"seqData\").innerHTML);\n");
430     htmlSvg.append("    var jalviewVersion = json['appSettings'].version;\n");
431     htmlSvg.append("    var url = json['appSettings'].webStartUrl;\n");
432     htmlSvg.append("    var myForm = document.createElement(\"form\");\n\n");
433     htmlSvg.append("    var heap = document.createElement(\"input\");\n");
434     htmlSvg.append("    heap.setAttribute(\"name\", \"jvm-max-heap\") ;\n");
435     htmlSvg.append("    heap.setAttribute(\"value\", \"2G\");\n\n");
436     htmlSvg.append("    var target = document.createElement(\"input\");\n");
437     htmlSvg.append("    target.setAttribute(\"name\", \"open\");\n");
438     htmlSvg.append("    target.setAttribute(\"value\", document.URL);\n\n");
439     htmlSvg.append("    var jvVersion = document.createElement(\"input\");\n");
440     htmlSvg.append("    jvVersion.setAttribute(\"name\", \"version\") ;\n");
441     htmlSvg.append("    jvVersion.setAttribute(\"value\", jalviewVersion);\n\n");
442     htmlSvg.append("    myForm.action = url;\n");
443     htmlSvg.append("    myForm.appendChild(heap);\n");
444     htmlSvg.append("    myForm.appendChild(target);\n");
445     htmlSvg.append("    myForm.appendChild(jvVersion);\n");
446     htmlSvg.append("    document.body.appendChild(myForm);\n");
447     htmlSvg.append("    myForm.submit() ;\n");
448     htmlSvg.append("    document.body.removeChild(myForm);\n");
449     htmlSvg.append("}\n");
450
451     // jquery facebox for displaying raw BioJSON data");
452     if (jsonData != null)
453     {
454       htmlSvg.append("/* Facebox (for jQuery)\n");
455       htmlSvg.append("* version: 1.3\n");
456       htmlSvg.append(" * @requires jQuery v1.2 or later\n");
457       htmlSvg.append(" * @homepage https://github.com/defunkt/facebox\n");
458       htmlSvg.append(" * Licensed under the MIT:\n");
459       htmlSvg.append(" *   http://www.opensource.org/licenses/mit-license.php\n");
460       htmlSvg.append(" * Copyright Forever Chris Wanstrath, Kyle Neath\n");
461       htmlSvg.append(" * Usage:\n");
462       htmlSvg.append(" *  jQuery(document).ready(function() {\n");
463       htmlSvg.append(" *    jQuery('a[rel*=facebox]').facebox()\n");
464       htmlSvg.append(" *  })\n");
465       htmlSvg.append(" *  <a href=\"#terms\" rel=\"facebox\">Terms</a>\n");
466       htmlSvg.append(" *    Loads the #terms div in the box\n");
467       htmlSvg.append(" *  <a href=\"terms.html\" rel=\"facebox\">Terms</a>\n");
468       htmlSvg.append(" *    Loads the terms.html page in the box\n");
469       htmlSvg.append(" *  <a href=\"terms.png\" rel=\"facebox\">Terms</a>\n");
470       htmlSvg.append(" *    Loads the terms.png image in the box\n");
471       htmlSvg.append(" *  You can also use it programmatically:\n");
472       htmlSvg.append(" *    jQuery.facebox('some html')\n");
473       htmlSvg.append(" *    jQuery.facebox('some html', 'my-groovy-style')\n");
474       htmlSvg.append(" *  The above will open a facebox with \"some html\" as the content.\n");
475       htmlSvg.append(" *    jQuery.facebox(function($) {\n");
476       htmlSvg.append(" *      $.get('blah.html', function(data) { $.facebox(data) })\n");
477       htmlSvg.append(" *    })\n");
478       htmlSvg.append(" *  The above will show a loading screen before the passed function is called,\n");
479       htmlSvg.append(" *  allowing for a better ajaxy experience.\n");
480       htmlSvg.append(" *  The facebox function can also display an ajax page, an image, or the contents of a div:\n");
481       htmlSvg.append(" *    jQuery.facebox({ ajax: 'remote.html' })\n");
482       htmlSvg.append(" *    jQuery.facebox({ ajax: 'remote.html' }, 'my-groovy-style')\n");
483       htmlSvg.append(" *    jQuery.facebox({ image: 'stairs.jpg' })\n");
484       htmlSvg.append(" *    jQuery.facebox({ image: 'stairs.jpg' }, 'my-groovy-style')\n");
485       htmlSvg.append(" *    jQuery.facebox({ div: '#box' })\n");
486       htmlSvg.append(" *    jQuery.facebox({ div: '#box' }, 'my-groovy-style')\n");
487       htmlSvg.append(" *    Want to close the facebox?  Trigger the 'close.facebox' document event:\n");
488       htmlSvg.append(" *    jQuery(document).trigger('close.facebox')\n");
489       htmlSvg.append(" *  Facebox also has a bunch of other hooks:\n");
490       htmlSvg.append(" *    loading.facebox\n");
491       htmlSvg.append(" *    beforeReveal.facebox\n");
492       htmlSvg.append(" *    reveal.facebox (aliased as 'afterReveal.facebox')\n");
493       htmlSvg.append(" *    init.facebox\n");
494       htmlSvg.append(" *    afterClose.facebox\n");
495       htmlSvg.append(" *  Simply bind a function to any of these hooks:\n");
496       htmlSvg.append(" *   $(document).bind('reveal.facebox', function() { ...stuff to do after the facebox and contents are revealed... })\n");
497       htmlSvg.append(" *\n");
498       htmlSvg.append(" */\n");
499       htmlSvg.append("(function($) {\n");
500       htmlSvg.append("  $.facebox = function(data, klass) {\n");
501       htmlSvg.append("    $.facebox.loading()\n");
502       htmlSvg.append("    if (data.ajax) fillFaceboxFromAjax(data.ajax, klass)\n");
503       htmlSvg.append("    else if (data.image) fillFaceboxFromImage(data.image, klass)\n");
504       htmlSvg.append("    else if (data.div) fillFaceboxFromHref(data.div, klass)\n");
505       htmlSvg.append("    else if ($.isFunction(data)) data.call($)\n");
506       htmlSvg.append("    else $.facebox.reveal(data, klass)\n");
507       htmlSvg.append("  }\n");
508
509       htmlSvg.append("  $.extend($.facebox, {\n");
510       htmlSvg.append("    settings: {\n");
511       htmlSvg.append("      opacity      : 0.2,\n");
512       htmlSvg.append("      overlay      : true,\n");
513       htmlSvg.append("      loadingImage : 'https://raw.githubusercontent.com/jalview/biojson/gh-pages/images/loading.gif',\n");
514       htmlSvg.append("      closeImage   : 'https://raw.githubusercontent.com/jalview/biojson/gh-pages/images/cancel.png',\n");
515       htmlSvg.append("      imageTypes   : [ 'png', 'jpg', 'jpeg', 'gif' ],\n");
516       htmlSvg.append("      faceboxHtml  : '<div  id=\"facebox\" style=\"display:none; width: 95%; height: 85%; overflow: auto;\"> ");
517       htmlSvg.append("      <div class=\"popup\"> ");
518       htmlSvg.append("        <div class=\"content\"> ");
519       htmlSvg.append("        </div> ");
520       htmlSvg.append("        <a href=\"#\" class=\"close\"></a> ");
521       htmlSvg.append("      </div> ");
522       htmlSvg.append("    </div>'\n");
523       htmlSvg.append("    },      \n");
524       htmlSvg.append("    loading: function() {\n");
525       htmlSvg.append("      init()\n");
526       htmlSvg.append("      if ($('#facebox .loading').length == 1) return true\n");
527       htmlSvg.append("      showOverlay()      \n");
528       htmlSvg.append("      $('#facebox .content').empty().\n");
529       htmlSvg.append("        append('<div class=\"loading\"><img src=\"'+$.facebox.settings.loadingImage+'\"/></div>')\n");
530       htmlSvg.append("      $('#facebox').show().css({\n");
531       htmlSvg.append("        top:    getPageScroll()[1] + (getPageHeight() / 10),\n");
532       htmlSvg.append("        left:    $(window).width() / 2 - ($('#facebox .popup').outerWidth() / 2)\n");
533       htmlSvg.append("      })      \n");
534       htmlSvg.append("      $(document).bind('keydown.facebox', function(e) {\n");
535       htmlSvg.append("       if (e.keyCode == 27) $.facebox.close()\n");
536       htmlSvg.append("        return true\n");
537       htmlSvg.append("      })\n");
538       htmlSvg.append("      $(document).trigger('loading.facebox')\n");
539       htmlSvg.append("    },\n");
540       htmlSvg.append("    reveal: function(data, klass) {\n");
541       htmlSvg.append("      $(document).trigger('beforeReveal.facebox')\n");
542       htmlSvg.append("      if (klass) $('#facebox .content').addClass(klass)\n");
543       htmlSvg.append("      $('#facebox .content').empty().append('<pre><code>'+JSON.stringify(JSON.parse(data),null,4)+'</pre></code>')\n");
544       htmlSvg.append("      $('#facebox .popup').children().fadeIn('normal')\n");
545       htmlSvg.append("      $('#facebox').css('left', $(window).width() / 2 - ($('#facebox .popup').outerWidth() / 2))\n");
546       htmlSvg.append("      $(document).trigger('reveal.facebox').trigger('afterReveal.facebox')\n");
547       htmlSvg.append("    },      \n");
548       htmlSvg.append("    close: function() {\n");
549       htmlSvg.append("      $(document).trigger('close.facebox')\n");
550       htmlSvg.append("      return false\n");
551       htmlSvg.append("    }\n");
552       htmlSvg.append("  })\n");
553       htmlSvg.append("  $.fn.facebox = function(settings) {\n");
554       htmlSvg.append("    if ($(this).length == 0) return    \n");
555       htmlSvg.append("    init(settings)      \n");
556       htmlSvg.append("    function clickHandler() {\n");
557       htmlSvg.append("      $.facebox.loading(true)      \n");
558       htmlSvg.append("      // support for rel=\"facebox.inline_popup\" syntax, to add a class\n");
559       htmlSvg.append("      // also supports deprecated \"facebox[.inline_popup]\" syntax\n");
560       htmlSvg.append("      var klass = this.rel.match(/facebox\\[?\\.(\\w+)\\]?/)\n");
561       htmlSvg.append("      if (klass) klass = klass[1]\n");
562       htmlSvg.append("      fillFaceboxFromHref(this.href, klass)\n");
563       htmlSvg.append("      return false\n");
564       htmlSvg.append("    }      \n");
565       htmlSvg.append("    return this.bind('click.facebox', clickHandler)\n");
566       htmlSvg.append("  }\n");
567       htmlSvg.append("  // called one time to setup facebox on this page\n");
568       htmlSvg.append("  function init(settings) {\n");
569       htmlSvg.append("    if ($.facebox.settings.inited) return true\n");
570       htmlSvg.append("    else $.facebox.settings.inited = true\n");
571       htmlSvg.append("    $(document).trigger('init.facebox')\n");
572       htmlSvg.append("    makeCompatible()\n");
573       htmlSvg.append("    var imageTypes = $.facebox.settings.imageTypes.join('|')\n");
574       htmlSvg.append("    $.facebox.settings.imageTypesRegexp = new RegExp('\\\\.(' + imageTypes + ')(\\\\?.*)?$', 'i')\n");
575
576       htmlSvg.append("    if (settings) $.extend($.facebox.settings, settings)\n");
577       htmlSvg.append("    $('body').append($.facebox.settings.faceboxHtml)\n");
578
579       htmlSvg.append("    var preload = [ new Image(), new Image() ]\n");
580       htmlSvg.append("    preload[0].src = $.facebox.settings.closeImage\n");
581       htmlSvg.append("    preload[1].src = $.facebox.settings.loadingImage\n");
582
583       htmlSvg.append("    $('#facebox').find('.b:first, .bl').each(function() {\n");
584       htmlSvg.append("      preload.push(new Image())\n");
585       htmlSvg.append("      preload.slice(-1).src = $(this).css('background-image').replace(/url\\((.+)\\)/, '$1')\n");
586       htmlSvg.append("    })\n");
587
588       htmlSvg.append("    $('#facebox .close')\n");
589       htmlSvg.append("      .click($.facebox.close)\n");
590       htmlSvg.append("      .append('<img src=\"'\n");
591       htmlSvg.append("              + $.facebox.settings.closeImage\n");
592       htmlSvg.append("              + '\" class=\"close_image\" title=\"close\">')\n");
593       htmlSvg.append("  }\n");
594
595       htmlSvg.append("  // getPageScroll() by quirksmode.com\n");
596       htmlSvg.append("  function getPageScroll() {\n");
597       htmlSvg.append("    var xScroll, yScroll;\n");
598       htmlSvg.append("    if (self.pageYOffset) {\n");
599       htmlSvg.append("      yScroll = self.pageYOffset;\n");
600       htmlSvg.append("      xScroll = self.pageXOffset;\n");
601       htmlSvg.append("    } else if (document.documentElement && document.documentElement.scrollTop) {     // Explorer 6 Strict\n");
602       htmlSvg.append("      yScroll = document.documentElement.scrollTop;\n");
603       htmlSvg.append("      xScroll = document.documentElement.scrollLeft;\n");
604       htmlSvg.append("    } else if (document.body) {// all other Explorers\n");
605       htmlSvg.append("      yScroll = document.body.scrollTop;\n");
606       htmlSvg.append("      xScroll = document.body.scrollLeft;\n");
607       htmlSvg.append("    }\n");
608       htmlSvg.append("    return new Array(xScroll,yScroll)\n");
609       htmlSvg.append("  }\n");
610
611       // Adapted from getPageSize() by quirksmode.com");
612       htmlSvg.append("  function getPageHeight() {\n");
613       htmlSvg.append("    var windowHeight\n");
614       htmlSvg.append("    if (self.innerHeight) {    // all except Explorer\n");
615       htmlSvg.append("      windowHeight = self.innerHeight;\n");
616       htmlSvg.append("    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode\n");
617       htmlSvg.append("      windowHeight = document.documentElement.clientHeight;\n");
618       htmlSvg.append("    } else if (document.body) { // other Explorers\n");
619       htmlSvg.append("      windowHeight = document.body.clientHeight;\n");
620       htmlSvg.append("    }\n");
621       htmlSvg.append("    return windowHeight\n");
622       htmlSvg.append("  }\n");
623
624       htmlSvg.append("  // Backwards compatibility\n");
625       htmlSvg.append("  function makeCompatible() {\n");
626       htmlSvg.append("    var $s = $.facebox.settings      \n");
627       htmlSvg.append("    $s.loadingImage = $s.loading_image || $s.loadingImage\n");
628       htmlSvg.append("    $s.closeImage = $s.close_image || $s.closeImage\n");
629       htmlSvg.append("    $s.imageTypes = $s.image_types || $s.imageTypes\n");
630       htmlSvg.append("    $s.faceboxHtml = $s.facebox_html || $s.faceboxHtml\n");
631       htmlSvg.append("  }\n");
632
633       htmlSvg.append("  // Figures out what you want to display and displays it\n");
634       htmlSvg.append("  // formats are:\n");
635       htmlSvg.append("  //     div: #id\n");
636       htmlSvg.append("  //   image: blah.extension\n");
637       htmlSvg.append("  //    ajax: anything else\n");
638       htmlSvg.append("  function fillFaceboxFromHref(href, klass) {\n");
639       htmlSvg.append("    // div\n");
640       htmlSvg.append("    if (href.match(/#/)) {\n");
641       htmlSvg.append("      var url    = window.location.href.split('#')[0]\n");
642       htmlSvg.append("      var target = href.replace(url,'')\n");
643       htmlSvg.append("      if (target == '#') return\n");
644       htmlSvg.append("      $.facebox.reveal($(target).html(), klass)\n");
645
646       htmlSvg.append("    // image\n");
647       htmlSvg.append("    } else if (href.match($.facebox.settings.imageTypesRegexp)) {\n");
648       htmlSvg.append("      fillFaceboxFromImage(href, klass)\n");
649       htmlSvg.append("    // ajax\n");
650       htmlSvg.append("    } else {\n");
651       htmlSvg.append("      fillFaceboxFromAjax(href, klass)\n");
652       htmlSvg.append("    }\n");
653       htmlSvg.append("  }\n");
654
655       htmlSvg.append("  function fillFaceboxFromImage(href, klass) {\n");
656       htmlSvg.append("    var image = new Image()\n");
657       htmlSvg.append("    image.onload = function() {\n");
658       htmlSvg.append("      $.facebox.reveal('<div class=\"image\"><img src=\"' + image.src + '\" /></div>', klass)\n");
659       htmlSvg.append("    }\n");
660       htmlSvg.append("    image.src = href\n");
661       htmlSvg.append("   }\n");
662
663       htmlSvg.append("  function fillFaceboxFromAjax(href, klass) {\n");
664       htmlSvg.append("    $.facebox.jqxhr = $.get(href, function(data) { $.facebox.reveal(data, klass) })\n");
665       htmlSvg.append("  }\n");
666
667       htmlSvg.append("  function skipOverlay() {\n");
668       htmlSvg.append("    return $.facebox.settings.overlay == false || $.facebox.settings.opacity === null\n");
669       htmlSvg.append("  }\n");
670
671       htmlSvg.append("  function showOverlay() {\n");
672       htmlSvg.append("    if (skipOverlay()) return\n");
673
674       htmlSvg.append("    if ($('#facebox_overlay').length == 0)\n");
675       htmlSvg.append("      $(\"body\").append('<div id=\"facebox_overlay\" class=\"facebox_hide\"></div>')\n");
676
677       htmlSvg.append("    $('#facebox_overlay').hide().addClass(\"facebox_overlayBG\")\n");
678       htmlSvg.append("      .css('opacity', $.facebox.settings.opacity)\n");
679       htmlSvg.append("      .click(function() { $(document).trigger('close.facebox') })\n");
680       htmlSvg.append("       .fadeIn(200)\n");
681       htmlSvg.append("    return false\n");
682       htmlSvg.append("  }\n");
683
684       htmlSvg.append("  function hideOverlay() {\n");
685       htmlSvg.append("    if (skipOverlay()) return      \n");
686       htmlSvg.append("    $('#facebox_overlay').fadeOut(200, function(){\n");
687       htmlSvg.append("      $(\"#facebox_overlay\").removeClass(\"facebox_overlayBG\")\n");
688       htmlSvg.append("      $(\"#facebox_overlay\").addClass(\"facebox_hide\")\n");
689       htmlSvg.append("      $(\"#facebox_overlay\").remove()\n");
690       htmlSvg.append("    })      \n");
691       htmlSvg.append("    return false\n");
692       htmlSvg.append("  }\n");
693
694       htmlSvg.append("  $(document).bind('close.facebox', function() {\n");
695       htmlSvg.append("    if ($.facebox.jqxhr) {\n");
696       htmlSvg.append("      $.facebox.jqxhr.abort()\n");
697       htmlSvg.append("      $.facebox.jqxhr = null\n");
698       htmlSvg.append("    }\n");
699       htmlSvg.append("    $(document).unbind('keydown.facebox')\n");
700       htmlSvg.append("    $('#facebox').fadeOut(function() {\n");
701       htmlSvg.append("      $('#facebox .content').removeClass().addClass('content')\n");
702       htmlSvg.append("      $('#facebox .loading').remove()\n");
703       htmlSvg.append("      $(document).trigger('afterClose.facebox')\n");
704       htmlSvg.append("    })\n");
705       htmlSvg.append("    hideOverlay()\n");
706       htmlSvg.append("  })\n");
707
708       htmlSvg.append("})(jQuery);\n");
709
710     }
711
712     htmlSvg.append("</script>\n");
713     htmlSvg.append("</html>");
714     return htmlSvg.toString();
715   }
716 }