use OOMwarning to warn user when out of Memory occurs
[jalview.git] / src / jalview / gui / AlignmentPanel.java
index 0cbdfbe..3dc967e 100755 (executable)
-package jalview.gui;\r
-\r
-import jalview.jbgui.GAlignmentPanel;\r
-import jalview.schemes.*;\r
-import jalview.analysis.*;\r
-import jalview.datamodel.*;\r
-import java.awt.*;\r
-import java.awt.event.*;\r
-import java.awt.print.*;\r
-import java.io.*;\r
-import java.awt.image.*;\r
-import org.jibble.epsgraphics.*;\r
-import javax.imageio.*;\r
-\r
-\r
-\r
-public class AlignmentPanel extends GAlignmentPanel implements AdjustmentListener, Printable\r
-{\r
-\r
-  AlignViewport     av;\r
-  OverviewPanel overviewPanel;\r
-  SeqPanel   seqPanel;\r
-  IdPanel    idPanel;\r
-  IdwidthAdjuster idwidthAdjuster;\r
-  public AlignFrame alignFrame;\r
-  ScalePanel scalePanel;\r
-  AnnotationPanel annotationPanel;\r
-  AnnotationLabels alabels;\r
-\r
-  // this value is set false when selection area being dragged\r
-  boolean fastPaint = true;\r
-\r
-  public AlignmentPanel(AlignFrame af, final AlignViewport av)\r
-  {\r
-    alignFrame = af;\r
-    this.av         = av;\r
-    seqPanel        = new SeqPanel  (av, this);\r
-    idPanel         = new IdPanel   (av, this);\r
-\r
-    scalePanel = new ScalePanel(av, this);\r
-\r
-    idPanelHolder.add(idPanel, BorderLayout.CENTER);\r
-    idwidthAdjuster = new IdwidthAdjuster(this);\r
-    idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);\r
-\r
-    annotationPanel = new AnnotationPanel(this);\r
-    alabels = new AnnotationLabels(this);\r
-\r
-    annotationSpaceFillerHolder.setPreferredSize(annotationPanel.getPreferredSize());\r
-    annotationScroller.setPreferredSize(annotationPanel.getPreferredSize());\r
-    annotationScroller.setViewportView(annotationPanel);\r
-    annotationSpaceFillerHolder.add(alabels, BorderLayout.CENTER);\r
-\r
-    Dimension d = calculateIdWidth();\r
-    d.setSize( d.width+4, d.height);\r
-    idPanel.idCanvas.setPreferredSize( d );\r
-    hscrollFillerPanel.setPreferredSize( d );\r
-\r
-    scalePanelHolder.add(scalePanel, BorderLayout.CENTER);\r
-    seqPanelHolder.add(seqPanel, BorderLayout.CENTER);\r
-\r
-    javax.swing.SwingUtilities.invokeLater(new Runnable()\r
-     {\r
-       public void run()\r
-       {\r
-         invalidate();\r
-         setScrollValues(0,0);\r
-         Dimension d = calculateIdWidth();\r
-         d.setSize( d.width+4, d.height);\r
-         idPanel.idCanvas.setPreferredSize( d );\r
-         RefreshPanels();\r
-       }\r
-    });\r
-\r
-\r
-    hscroll.addAdjustmentListener(this);\r
-    vscroll.addAdjustmentListener(this);\r
-\r
-    addComponentListener(new ComponentAdapter()\r
-   {\r
-     public void componentResized(ComponentEvent evt)\r
-     {\r
-          RefreshPanels();\r
-     }\r
-   });\r
-\r
-   setFocusable(true);\r
-   addKeyListener(new KeyAdapter()\r
-   {\r
-     public void keyPressed(KeyEvent evt)\r
-     {\r
-       switch(evt.getKeyCode())\r
-       {\r
-         case  27: // escape key\r
-           av.setSelectionGroup(null);\r
-           RefreshPanels();\r
-           break;\r
-         case KeyEvent.VK_X:\r
-           if(evt.isControlDown())\r
-           alignFrame.cut_actionPerformed(null);\r
-           break;\r
-         case KeyEvent.VK_C:\r
-         if(evt.isControlDown())\r
-           alignFrame.copy_actionPerformed(null);\r
-           break;\r
-         case KeyEvent.VK_V:\r
-          if(evt.isControlDown())\r
-           alignFrame.paste(true);\r
-           break;\r
-         case KeyEvent.VK_A:\r
-         if(evt.isControlDown())\r
-           alignFrame.selectAllSequenceMenuItem_actionPerformed(null);\r
-           break;\r
-        case KeyEvent.VK_DOWN:\r
-          alignFrame.moveSelectedSequences(false);\r
-          break;\r
-        case KeyEvent.VK_UP:\r
-          alignFrame.moveSelectedSequences(true);\r
-          break;\r
-        case KeyEvent.VK_F:\r
-         if(evt.isControlDown())\r
-          alignFrame.findMenuItem_actionPerformed(null);\r
-          break;\r
-       }\r
-     }\r
-   });\r
-  }\r
-\r
-  Dimension calculateIdWidth()\r
-  {\r
-    Graphics g = this.getGraphics();\r
-    if(g==null)\r
-    {\r
-      javax.swing.JFrame f = new javax.swing.JFrame();\r
-      f.addNotify();\r
-      g = f.getGraphics();\r
-    }\r
-\r
-    FontMetrics fm = g.getFontMetrics(av.font);\r
-    AlignmentI al = av.getAlignment();\r
-\r
-       int i   = 0;\r
-       int idWidth = 0;\r
-       String id;\r
-       while (i < al.getHeight() && al.getSequenceAt(i) != null)\r
-       {\r
-         SequenceI s   = al.getSequenceAt(i);\r
-         if(av.getShowFullId())\r
-           id   = s.getDisplayId();\r
-         else\r
-           id = s.getName();\r
-\r
-         if (fm.stringWidth(id) > idWidth)\r
-           idWidth = fm.stringWidth(id);\r
-         i++;\r
-       }\r
-\r
-       // Also check annotation label widths\r
-       i=0;\r
-       if(al.getAlignmentAnnotation()!=null)\r
-       {\r
-         fm = g.getFontMetrics(alabels.getFont());\r
-         while (i < al.getAlignmentAnnotation().length)\r
-         {\r
-           String label = al.getAlignmentAnnotation()[i].label;\r
-           if (fm.stringWidth(label) > idWidth)\r
-             idWidth = fm.stringWidth(label);\r
-           i++;\r
-         }\r
-       }\r
-\r
-       return new Dimension(idWidth, 12);\r
-  }\r
-\r
-\r
- public void highlightSearchResults(int [] results)\r
- {\r
-   seqPanel.seqCanvas.highlightSearchResults( results );\r
-\r
-   // do we need to scroll the panel?\r
-   if(results!=null && (av.getStartSeq()>results[0]\r
-                        || av.getEndSeq()<results[0]\r
-                        || av.getStartRes()>results[1]\r
-                        || av.getEndRes()<results[2]))\r
-       setScrollValues(results[1], results[0]);\r
-\r
-\r
- }\r
-\r
-\r
- public OverviewPanel getOverviewPanel()\r
- {\r
-   return overviewPanel;\r
- }\r
-\r
- public void setOverviewPanel(OverviewPanel op)\r
- {\r
-   overviewPanel = op;\r
- }\r
-\r
-\r
-  public void setAnnotationVisible(boolean b)\r
-  {\r
-    annotationSpaceFillerHolder.setVisible(b);\r
-    annotationScroller.setVisible(b);\r
-    javax.swing.SwingUtilities.invokeLater(new Runnable()\r
-     {\r
-       public void run()\r
-       {\r
-         RefreshPanels();\r
-       }\r
-    });\r
-\r
-  }\r
-\r
-\r
-  public void setWrapAlignment(boolean wrap)\r
-  {\r
-    scalePanelHolder.setVisible(!wrap);\r
-    hscroll.setVisible(!wrap);\r
-    idwidthAdjuster.setVisible(!wrap);\r
-\r
-    av.setShowAnnotation(!wrap);\r
-    annotationScroller.setVisible(!wrap);\r
-    annotationSpaceFillerHolder.setVisible(!wrap);\r
-    idSpaceFillerPanel1.setVisible(!wrap);\r
-    javax.swing.SwingUtilities.invokeLater(new Runnable()\r
-     {\r
-       public void run()\r
-       {\r
-         RefreshPanels();\r
-       }\r
-    });\r
-\r
-  }\r
-\r
-\r
-  public void setColourScheme()\r
-  {\r
-    ColourSchemeI cs = av.getGlobalColourScheme();\r
-\r
-    if(av.getConservationSelected())\r
-    {\r
-\r
-       Alignment al = (Alignment)av.getAlignment();\r
-       Conservation c = new Conservation("All",\r
-                            ResidueProperties.propHash, 3, al.getSequences(), 0,\r
-                            al.getWidth() );\r
-\r
-       c.calculate();\r
-       c.verdict(false, av.ConsPercGaps);\r
-       ConservationColourScheme ccs = new ConservationColourScheme(c, cs);\r
-\r
-       av.setGlobalColourScheme( ccs );\r
-\r
-    }\r
-\r
-    RefreshPanels();\r
-  }\r
-\r
-\r
-  public void RefreshPanels()\r
-  {\r
-\r
-    Dimension d = idPanel.idCanvas.getPreferredSize();\r
-    idPanelHolder.setPreferredSize(d);\r
-    hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));\r
-\r
-    if (av.getWrapAlignment())\r
-    {\r
-      int max = av.alignment.getWidth() / seqPanel.seqCanvas.getWrappedCanvasWidth(seqPanel.seqCanvas.getWidth());\r
-      vscroll.setValues(0, 1, 0, max);\r
-    }\r
-    else\r
-    {\r
-      if (overviewPanel != null)\r
-        overviewPanel.updateOverviewImage();\r
-      setScrollValues(av.getStartRes(), av.getStartSeq());\r
-    }\r
-\r
-    validate();\r
-    repaint();\r
-  }\r
-\r
-\r
-  int hextent = 0;\r
-  int vextent = 0;\r
-\r
-  // return value is true if the scroll is valid\r
-  public boolean scrollUp(boolean up)\r
-  {\r
-    if(up)\r
-    {\r
-      if(vscroll.getValue()<1)\r
-        return false;\r
-      fastPaint  = false;\r
-      vscroll.setValue(vscroll.getValue() - 1);\r
-    }\r
-    else\r
-    {\r
-     if(vextent+vscroll.getValue() >= av.getAlignment().getHeight())\r
-       return false;\r
-      fastPaint  = false;\r
-      vscroll.setValue(vscroll.getValue() + 1);\r
-    }\r
-    fastPaint = true;\r
-    return true;\r
-  }\r
-\r
-  public boolean scrollRight(boolean right)\r
-  {\r
-\r
-    if (right)\r
-    {\r
-      if (hscroll.getValue() < 1)\r
-        return false;\r
-      fastPaint = false;\r
-      hscroll.setValue(hscroll.getValue() - 1);\r
-    }\r
-    else\r
-    {\r
-      if (hextent + hscroll.getValue() >= av.getAlignment().getWidth())\r
-        return false;\r
-      fastPaint = false;\r
-      hscroll.setValue(hscroll.getValue() + 1);\r
-    }\r
-    fastPaint = true;\r
-    return true;\r
-  }\r
-\r
-\r
-  public void setScrollValues(int x, int y)\r
-  {\r
-    hextent = seqPanel.seqCanvas.getWidth()/av.charWidth;\r
-    vextent = seqPanel.seqCanvas.getHeight()/av.charHeight;\r
-\r
-    if(hextent > av.alignment.getWidth())\r
-      hextent = av.alignment.getWidth();\r
-    if(vextent > av.alignment.getHeight())\r
-      vextent = av.alignment.getHeight();\r
-\r
-    if(hextent+x  >  av.getAlignment().getWidth())\r
-      x =  av.getAlignment().getWidth()- hextent;\r
-\r
-    if(vextent+y > av.getAlignment().getHeight())\r
-      y = av.getAlignment().getHeight() - vextent;\r
-\r
-    if(y<0)\r
-      y = 0;\r
-\r
-    if(x<0)\r
-      x=0;\r
-\r
-    hscroll.setValues(x,hextent,0,av.getAlignment().getWidth());\r
-    vscroll.setValues(y,vextent,0,av.getAlignment().getHeight() );\r
-\r
-  }\r
-\r
-\r
-  public void adjustmentValueChanged(AdjustmentEvent evt)\r
-  {\r
-    int oldX = av.getStartRes();\r
-    int oldY = av.getStartSeq();\r
-\r
-    if (evt.getSource() == hscroll)\r
-    {\r
-      int x = hscroll.getValue();\r
-      av.setStartRes(x);\r
-      av.setEndRes(x + seqPanel.seqCanvas.getWidth()/av.getCharWidth()-1);\r
-    }\r
-\r
-    if (evt.getSource() == vscroll)\r
-    {\r
-      int offy = vscroll.getValue();\r
-      if (av.getWrapAlignment())\r
-      {\r
-        int rowSize = seqPanel.seqCanvas.getWrappedCanvasWidth(seqPanel.seqCanvas.getWidth());\r
-        av.setStartRes( vscroll.getValue() * rowSize );\r
-        av.setEndRes( (vscroll.getValue()+1) * rowSize );\r
-      }\r
-      else\r
-      {\r
-        av.setStartSeq(offy);\r
-        av.setEndSeq(offy + seqPanel.seqCanvas.getHeight() / av.getCharHeight());\r
-      }\r
-    }\r
-\r
-\r
-    if(overviewPanel!=null)\r
-      overviewPanel.setBoxPosition();\r
-\r
-    if(av.getWrapAlignment() || !fastPaint)\r
-      repaint();\r
-    else\r
-    {\r
-      seqPanel.seqCanvas.fastPaint(av.getStartRes() - oldX,\r
-                                   av.getStartSeq() - oldY);\r
-      idPanel.idCanvas.fastPaint(av.getStartSeq() - oldY);\r
-      scalePanel.repaint();\r
-      if (av.getShowAnnotation())\r
-        annotationPanel.fastPaint(av.getStartRes() - oldX);\r
-    }\r
-\r
-  }\r
-\r
-  public int print(Graphics pg, PageFormat pf, int pi) throws PrinterException\r
-  {\r
-    pg.translate((int)pf.getImageableX(), (int)pf.getImageableY());\r
-\r
-    int pwidth = (int) pf.getImageableWidth();\r
-    int pheight = (int) pf.getImageableHeight();\r
-\r
-    if (av.getWrapAlignment())\r
-      return printWrappedAlignment(pg, pwidth,pheight, pi);\r
-    else\r
-      return printUnwrapped(pg,pwidth, pheight,pi);\r
-  }\r
-\r
-  public int printUnwrapped(Graphics pg, int pwidth, int pheight, int pi) throws PrinterException\r
-  {\r
-\r
-    int idWidth = calculateIdWidth().width + 4;\r
-\r
-\r
-    pg.setColor(Color.white);\r
-    pg.fillRect(0,0,pwidth, pheight);\r
-    pg.setFont( av.getFont() );\r
-\r
-    ////////////////////////////////////\r
-    /// How many sequences and residues can we fit on a printable page?\r
-    int totalRes = (pwidth - idWidth)/av.getCharWidth();\r
-    int totalSeq = (int)((pheight - 30)/av.getCharHeight())-1;\r
-    int pagesWide = av.getAlignment().getWidth() / totalRes +1;\r
-    int pagesHigh = av.getAlignment().getHeight() / totalSeq +1;\r
-\r
-    if (pi >= pagesWide*pagesHigh)\r
-     return Printable.NO_SUCH_PAGE;\r
-\r
-    /////////////////////////////\r
-    /// Only print these sequences and residues on this page\r
-    int startRes, endRes, startSeq, endSeq;\r
-    startRes = (pi % pagesWide) * totalRes;\r
-    endRes = startRes + totalRes-1;\r
-    if(endRes>av.getAlignment().getWidth())\r
-      endRes = av.getAlignment().getWidth();\r
-\r
-     startSeq = (pi / pagesWide) * totalSeq;\r
-     endSeq = startSeq + totalSeq;\r
-     if(endSeq > av.getAlignment().getHeight())\r
-       endSeq = av.getAlignment().getHeight();\r
-\r
-\r
-    ////////////////\r
-    //draw Scale\r
-    pg.translate(idWidth,0);\r
-    scalePanel.drawScale(pg, startRes, endRes, pwidth-idWidth);\r
-\r
-    pg.translate(-idWidth, 30);\r
-    ////////////////\r
-    // Draw the ids\r
-    Color currentColor=null;\r
-    Color currentTextColor=null;\r
-    for(int i=startSeq; i<endSeq; i++)\r
-    {\r
-      if (av.getSelectionGroup()!=null && av.getSelectionGroup().sequences.contains(av.getAlignment().getSequenceAt(i)))\r
-      {\r
-        currentColor = Color.gray;\r
-        currentTextColor = Color.black;\r
-      }\r
-      else\r
-      {\r
-        currentColor = av.getAlignment().getSequenceAt(i).getColor();\r
-        currentTextColor = Color.black;\r
-      }\r
-\r
-      pg.setColor(currentColor);\r
-      pg.fillRect(0,  jalview.analysis.AlignmentUtil.getPixelHeight(startSeq, i, av.getCharHeight()),\r
-                              idWidth,\r
-                              av.getCharHeight());\r
-\r
-      pg.setColor(currentTextColor);\r
-\r
-      String string = av.getAlignment().getSequenceAt(i).getName();\r
-      if(av.getShowFullId())\r
-        string = av.getAlignment().getSequenceAt(i).getDisplayId();\r
-\r
-      pg.drawString(string, 0,  jalview.analysis.AlignmentUtil.getPixelHeight\r
-                    (startSeq, i, av.getCharHeight()) + av.getCharHeight() - (av.getCharHeight() / 5));\r
-    }\r
-\r
-    // draw main sequence panel\r
-    pg.translate(idWidth,0);\r
-    seqPanel.seqCanvas.drawPanel(pg,startRes,endRes,startSeq,endSeq,startRes,startSeq,0);\r
-\r
-\r
-    if(av.getShowAnnotation())\r
-      {\r
-        pg.translate(-idWidth,(endSeq-startSeq)*av.charHeight);\r
-        alabels.drawComponent((Graphics2D)pg);\r
-        pg.translate(idWidth,0);\r
-        annotationPanel.drawComponent((Graphics2D) pg, startRes, endRes+1);\r
-      }\r
-\r
-    return Printable.PAGE_EXISTS;\r
-  }\r
-\r
-\r
-  public int printWrappedAlignment(Graphics pg, int pwidth, int pheight, int pi) throws PrinterException\r
-  {\r
-\r
-    int idWidth = calculateIdWidth().width+4;\r
-\r
-    if( seqPanel.seqCanvas.getWidth() < pwidth-idWidth)\r
-      pwidth = seqPanel.seqCanvas.getWidth() + idWidth;\r
-\r
-\r
-    pg.setColor(Color.white);\r
-    pg.fillRect(0,0,pwidth, pheight);\r
-    pg.setFont( av.getFont() );\r
-\r
-    ////////////////////////////////////\r
-    /// How many sequences and residues can we fit on a printable page?\r
-    AlignmentI da = av.alignment;\r
-    int endy   = da.getHeight();\r
-    int chunkHeight =  (da.getHeight() + 2)*av.charHeight;\r
-    int chunkWidth  =   (pwidth-idWidth)/av.charWidth;\r
-\r
-    int noChunksOnPage = pheight / chunkHeight;\r
-    int totalChunks = da.getWidth() / chunkWidth;\r
-\r
-    if ( pi*noChunksOnPage > totalChunks )\r
-     return Printable.NO_SUCH_PAGE;\r
-\r
-    ////////////////\r
-    // Draw the ids\r
-    pg.setClip(0,0,pwidth, noChunksOnPage*chunkHeight);\r
-\r
-    pg.setColor(Color.black);\r
-\r
-    int rowSize =  av.getEndRes() - av.getStartRes();\r
-    // Draw the rest of the panels\r
-\r
-    for(int ypos=2*av.charHeight, row=av.getEndRes(); row<av.alignment.getWidth();\r
-        ypos += av.chunkHeight, row+=rowSize )\r
-    {\r
-      for (int i = 0; i < endy; i++)\r
-      {\r
-        SequenceI s = da.getSequenceAt(i);\r
-        String string = s.getName();\r
-        if (av.getShowFullId())\r
-          string = s.getDisplayId();\r
-\r
-        pg.drawString(string, 0,\r
-                      AlignmentUtil.getPixelHeight(0, i, av.charHeight) + ypos +\r
-                      av.charHeight - (av.charHeight / 5));\r
-      }\r
-    }\r
-\r
-    // draw main sequence panel\r
-    pg.translate(idWidth,0);\r
-    seqPanel.seqCanvas.drawWrappedPanel(pg, pwidth-idWidth, pheight, pi*noChunksOnPage*chunkWidth);\r
-\r
-\r
-    return Printable.PAGE_EXISTS;\r
-\r
-  }\r
-\r
-\r
-  public void makeEPS()\r
-  {\r
-    int height = (av.alignment.getWidth() / av.getChunkWidth() +1) * av.chunkHeight;\r
-    int width = seqPanel.getWidth() + idPanel.getWidth();\r
-\r
-    if (!av.getWrapAlignment())\r
-    {\r
-      height = (av.alignment.getHeight()+1) * av.charHeight + 30;\r
-      width = idPanel.getWidth() + av.alignment.getWidth() * av.charWidth;\r
-    }\r
-    if(av.getShowAnnotation())\r
-   {\r
-     height += annotationPanel.getPreferredSize().height;\r
-   }\r
-\r
-    try\r
-    {\r
-      jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(jalview.bin.Cache.getProperty(\r
-          "LAST_DIRECTORY"), new String[]{"eps"}, "Encapsulated Postscript");\r
-      chooser.setFileView(new jalview.io.JalviewFileView());\r
-      chooser.setDialogTitle("Create EPS file from alignment");\r
-      chooser.setToolTipText("Save");\r
-\r
-      int value = chooser.showSaveDialog(this);\r
-      if (value != jalview.io.JalviewFileChooser.APPROVE_OPTION)\r
-        return;\r
-\r
-      jalview.bin.Cache.setProperty("LAST_DIRECTORY",chooser.getSelectedFile().getPath());\r
-      FileOutputStream out = new FileOutputStream(chooser.getSelectedFile());\r
-      EpsGraphics2D pg = new EpsGraphics2D("Example", out, 0, 0, width, height);\r
-\r
-        if (av.getWrapAlignment())\r
-          printWrappedAlignment(pg, width, height, 0);\r
-        else\r
-          printUnwrapped(pg, width, height, 0);\r
-\r
-\r
-        pg.flush();\r
-        pg.close();\r
-    }\r
-    catch (Exception ex)\r
-    {\r
-      ex.printStackTrace();\r
-    }\r
-  }\r
-\r
-  public void makePNG()\r
-  {\r
-      int height = (av.alignment.getWidth() / av.getChunkWidth() +1) * av.chunkHeight;\r
-      int width = seqPanel.getWidth() + idPanel.getWidth();\r
-\r
-      if (!av.getWrapAlignment())\r
-      {\r
-        height = (av.alignment.getHeight()+1) * av.charHeight + 30;\r
-        width = idPanel.getWidth() + av.alignment.getWidth() * av.charWidth;\r
-      }\r
-\r
-      if(av.getShowAnnotation())\r
-      {\r
-        height += annotationPanel.getPreferredSize().height;\r
-      }\r
-\r
-\r
-System.out.println(width +" "+height);\r
-\r
-    try\r
-    {\r
-      jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(jalview.bin.Cache.getProperty(\r
-          "LAST_DIRECTORY"), new String[]{"png"}, "Portable network graphics");\r
-      chooser.setFileView(new jalview.io.JalviewFileView());\r
-      chooser.setDialogTitle("Create EPS file from alignment");\r
-      chooser.setToolTipText("Save");\r
-\r
-      int value = chooser.showSaveDialog(this);\r
-      if (value != jalview.io.JalviewFileChooser.APPROVE_OPTION)\r
-        return;\r
-\r
-      jalview.bin.Cache.setProperty("LAST_DIRECTORY",chooser.getSelectedFile().getPath());\r
-      FileOutputStream out = new FileOutputStream(chooser.getSelectedFile());\r
-\r
-      BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);\r
-      Graphics png = bi.getGraphics();\r
-\r
-\r
-        if (av.getWrapAlignment())\r
-          printWrappedAlignment(png, width, height, 0);\r
-        else\r
-          printUnwrapped(png, width, height, 0);\r
-\r
-        ImageIO.write(bi, "png", out);\r
-        out.close();\r
-    }\r
-    catch (Exception ex)\r
-    {\r
-      ex.printStackTrace();\r
-    }\r
-  }\r
-\r
-}\r
-\r
-\r
-\r
-\r
+/*
+ * Jalview - A Sequence Alignment Editor and Viewer (Version 2.4)
+ * Copyright (C) 2008 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
+ * 
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ * 
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ * 
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
+ */
+package jalview.gui;
+
+import java.beans.*;
+import java.io.*;
+
+import java.awt.*;
+import java.awt.event.*;
+import java.awt.print.*;
+import javax.swing.*;
+
+import jalview.datamodel.*;
+import jalview.jbgui.*;
+import jalview.schemes.*;
+
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
+public class AlignmentPanel
+    extends GAlignmentPanel implements AdjustmentListener, Printable
+{
+  public AlignViewport av;
+  OverviewPanel overviewPanel;
+  SeqPanel seqPanel;
+  IdPanel idPanel;
+  IdwidthAdjuster idwidthAdjuster;
+
+  /** DOCUMENT ME!! */
+  public AlignFrame alignFrame;
+  ScalePanel scalePanel;
+  AnnotationPanel annotationPanel;
+  AnnotationLabels alabels;
+
+  // this value is set false when selection area being dragged
+  boolean fastPaint = true;
+  int hextent = 0;
+  int vextent = 0;
+
+  /**
+   * Creates a new AlignmentPanel object.
+   *
+   * @param af DOCUMENT ME!
+   * @param av DOCUMENT ME!
+   */
+  public AlignmentPanel(AlignFrame af, final AlignViewport av)
+  {
+    alignFrame = af;
+    this.av = av;
+    seqPanel = new SeqPanel(av, this);
+    idPanel = new IdPanel(av, this);
+
+    scalePanel = new ScalePanel(av, this);
+
+    idPanelHolder.add(idPanel, BorderLayout.CENTER);
+    idwidthAdjuster = new IdwidthAdjuster(this);
+    idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
+
+    annotationPanel = new AnnotationPanel(this);
+    alabels = new AnnotationLabels(this);
+
+    annotationScroller.setViewportView(annotationPanel);
+    annotationSpaceFillerHolder.add(alabels, BorderLayout.CENTER);
+
+    scalePanelHolder.add(scalePanel, BorderLayout.CENTER);
+    seqPanelHolder.add(seqPanel, BorderLayout.CENTER);
+
+    setScrollValues(0, 0);
+
+    setAnnotationVisible(av.getShowAnnotation());
+
+    hscroll.addAdjustmentListener(this);
+    vscroll.addAdjustmentListener(this);
+
+    final AlignmentPanel ap = this;
+    av.addPropertyChangeListener(new PropertyChangeListener()
+    {
+      public void propertyChange(PropertyChangeEvent evt)
+      {
+        if (evt.getPropertyName().equals("alignment"))
+        {
+          PaintRefresher.Refresh(ap,
+                                 av.getSequenceSetId(),
+                                 true,
+                                 true);
+          alignmentChanged();
+        }
+      }
+    });
+
+    fontChanged();
+    adjustAnnotationHeight();
+
+  }
+
+  public void alignmentChanged()
+  {
+    av.alignmentChanged(this);
+
+    alignFrame.updateEditMenuBar();
+
+    paintAlignment(true);
+
+  }
+
+  /**
+   * DOCUMENT ME!
+   */
+  public void fontChanged()
+  {
+    // set idCanvas bufferedImage to null
+    // to prevent drawing old image
+    FontMetrics fm = getFontMetrics(av.getFont());
+
+    scalePanelHolder.setPreferredSize(new Dimension(10,
+        av.charHeight + fm.getDescent()));
+    idSpaceFillerPanel1.setPreferredSize(new Dimension(10,
+        av.charHeight + fm.getDescent()));
+
+    idPanel.idCanvas.gg = null;
+    seqPanel.seqCanvas.img = null;
+    annotationPanel.adjustPanelHeight();
+
+    Dimension d = calculateIdWidth();
+    d.setSize(d.width + 4, d.height);
+    idPanel.idCanvas.setPreferredSize(d);
+    hscrollFillerPanel.setPreferredSize(d);
+
+    if (overviewPanel != null)
+    {
+      overviewPanel.setBoxPosition();
+    }
+
+    repaint();
+  }
+
+  /**
+   * Calculate the width of the alignment labels based on the displayed names and any bounds on label width set in preferences.
+   *
+   * @return Dimension giving the maximum width of the alignment label panel that should be used.
+   */
+  public Dimension calculateIdWidth()
+  {
+    Container c = new Container();
+
+    FontMetrics fm = c.getFontMetrics(
+        new Font(av.font.getName(), Font.ITALIC, av.font.getSize()));
+
+    AlignmentI al = av.getAlignment();
+    int afwidth = (alignFrame!=null ? alignFrame.getWidth() : 300); 
+    int maxwidth = Math.max(20,Math.min(afwidth-200,(int) 2*afwidth/3));  
+    int i = 0;
+    int idWidth = 0;
+    String id;
+
+    while ( (i < al.getHeight()) && (al.getSequenceAt(i) != null))
+    {
+      SequenceI s = al.getSequenceAt(i);
+
+      id = s.getDisplayId(av.getShowJVSuffix());
+
+      if (fm.stringWidth(id) > idWidth)
+      {
+        idWidth = fm.stringWidth(id);
+      }
+
+      i++;
+    }
+
+    // Also check annotation label widths
+    i = 0;
+
+    if (al.getAlignmentAnnotation() != null)
+    {
+      fm = c.getFontMetrics(alabels.getFont());
+
+      while (i < al.getAlignmentAnnotation().length)
+      {
+        String label = al.getAlignmentAnnotation()[i].label;
+
+        if (fm.stringWidth(label) > idWidth)
+        {
+          idWidth = fm.stringWidth(label);
+        }
+
+        i++;
+      }
+    }
+
+    return new Dimension(Math.min(maxwidth, idWidth), 12);
+  }
+
+  /**
+   * DOCUMENT ME!
+   *
+   * @param results DOCUMENT ME!
+   */
+  public void highlightSearchResults(SearchResults results)
+  {
+    seqPanel.seqCanvas.highlightSearchResults(results);
+
+    // do we need to scroll the panel?
+    if (results != null)
+    {
+      SequenceI seq = results.getResultSequence(0);
+      int seqIndex = av.alignment.findIndex(seq);
+      int start = seq.findIndex(results.getResultStart(0)) - 1;
+      int end = seq.findIndex(results.getResultEnd(0)) - 1;
+
+      if (!av.wrapAlignment)
+      {
+        if ( (av.getStartRes() > end) || (av.getEndRes() < start) ||
+            ( (av.getStartSeq() > seqIndex) || (av.getEndSeq() < seqIndex)))
+        {
+          setScrollValues(start, seqIndex);
+        }
+      }
+      else
+      {
+        scrollToWrappedVisible(start);
+      }
+    }
+
+    paintAlignment(true);
+  }
+
+  void scrollToWrappedVisible(int res)
+  {
+    int cwidth = seqPanel.seqCanvas.getWrappedCanvasWidth(seqPanel.seqCanvas.
+        getWidth());
+    if (res <= av.getStartRes() || res >= (av.getStartRes() + cwidth))
+    {
+      vscroll.setValue(res / cwidth);
+      av.startRes = vscroll.getValue() * cwidth;
+    }
+  }
+
+  /**
+   * DOCUMENT ME!
+   *
+   * @return DOCUMENT ME!
+   */
+  public OverviewPanel getOverviewPanel()
+  {
+    return overviewPanel;
+  }
+
+  /**
+   * DOCUMENT ME!
+   *
+   * @param op DOCUMENT ME!
+   */
+  public void setOverviewPanel(OverviewPanel op)
+  {
+    overviewPanel = op;
+  }
+
+  /**
+   * DOCUMENT ME!
+   *
+   * @param b DOCUMENT ME!
+   */
+  public void setAnnotationVisible(boolean b)
+  {
+    if (!av.wrapAlignment)
+    {
+      annotationSpaceFillerHolder.setVisible(b);
+      annotationScroller.setVisible(b);
+    }
+    repaint();
+  }
+
+  public void adjustAnnotationHeight()
+  {
+    //TODO: display vertical annotation scrollbar if necessary 
+    // this is called after loading new annotation onto alignment
+    if (alignFrame.getHeight() == 0)
+    {
+      System.out.println("NEEDS FIXING");
+    }
+
+    int height = annotationPanel.adjustPanelHeight();
+
+    if (hscroll.isVisible())
+    {
+      height += hscroll.getPreferredSize().height;
+    }
+    if (height > alignFrame.getHeight() / 2)
+    {
+      height = alignFrame.getHeight() / 2;
+    }
+
+    hscroll.addNotify();
+
+    annotationScroller.setPreferredSize(
+        new Dimension(annotationScroller.getWidth(), height));
+
+
+    annotationSpaceFillerHolder.setPreferredSize(new Dimension(
+        annotationSpaceFillerHolder.getWidth(),
+        height));
+    annotationScroller.validate();// repaint();
+    repaint();
+  }
+
+  /**
+   * DOCUMENT ME!
+   *
+   * @param wrap DOCUMENT ME!
+   */
+  public void setWrapAlignment(boolean wrap)
+  {
+    av.startSeq = 0;
+    scalePanelHolder.setVisible(!wrap);
+    hscroll.setVisible(!wrap);
+    idwidthAdjuster.setVisible(!wrap);
+
+    if (wrap)
+    {
+      annotationScroller.setVisible(false);
+      annotationSpaceFillerHolder.setVisible(false);
+    }
+    else if (av.showAnnotation)
+    {
+      annotationScroller.setVisible(true);
+      annotationSpaceFillerHolder.setVisible(true);
+    }
+
+    idSpaceFillerPanel1.setVisible(!wrap);
+
+    repaint();
+  }
+
+  // return value is true if the scroll is valid
+  public boolean scrollUp(boolean up)
+  {
+    if (up)
+    {
+      if (vscroll.getValue() < 1)
+      {
+        return false;
+      }
+
+      fastPaint = false;
+      vscroll.setValue(vscroll.getValue() - 1);
+    }
+    else
+    {
+      if ( (vextent + vscroll.getValue()) >= av.getAlignment().getHeight())
+      {
+        return false;
+      }
+
+      fastPaint = false;
+      vscroll.setValue(vscroll.getValue() + 1);
+    }
+
+    fastPaint = true;
+
+    return true;
+  }
+
+  /**
+   * DOCUMENT ME!
+   *
+   * @param right DOCUMENT ME!
+   *
+   * @return DOCUMENT ME!
+   */
+  public boolean scrollRight(boolean right)
+  {
+    if (!right)
+    {
+      if (hscroll.getValue() < 1)
+      {
+        return false;
+      }
+
+      fastPaint = false;
+      hscroll.setValue(hscroll.getValue() - 1);
+    }
+    else
+    {
+      if ( (hextent + hscroll.getValue()) >= av.getAlignment().getWidth())
+      {
+        return false;
+      }
+
+      fastPaint = false;
+      hscroll.setValue(hscroll.getValue() + 1);
+    }
+
+    fastPaint = true;
+
+    return true;
+  }
+
+  /**
+   * DOCUMENT ME!
+   *
+   * @param x DOCUMENT ME!
+   * @param y DOCUMENT ME!
+   */
+  public void setScrollValues(int x, int y)
+  {
+
+    int width = av.alignment.getWidth();
+    int height = av.alignment.getHeight();
+
+    if (av.hasHiddenColumns)
+    {
+      width = av.getColumnSelection().findColumnPosition(width);
+    }
+
+    av.setEndRes( (x + (seqPanel.seqCanvas.getWidth() / av.charWidth)) - 1);
+
+    hextent = seqPanel.seqCanvas.getWidth() / av.charWidth;
+    vextent = seqPanel.seqCanvas.getHeight() / av.charHeight;
+
+    if (hextent > width)
+    {
+      hextent = width;
+    }
+
+    if (vextent > height)
+    {
+      vextent = height;
+    }
+
+    if ( (hextent + x) > width)
+    {
+      x = width - hextent;
+    }
+
+    if ( (vextent + y) > height)
+    {
+      y = height - vextent;
+    }
+
+    if (y < 0)
+    {
+      y = 0;
+    }
+
+    if (x < 0)
+    {
+      x = 0;
+    }
+
+    hscroll.setValues(x, hextent, 0, width);
+    vscroll.setValues(y, vextent, 0, height);
+  }
+
+  /**
+   * DOCUMENT ME!
+   *
+   * @param evt DOCUMENT ME!
+   */
+  public void adjustmentValueChanged(AdjustmentEvent evt)
+  {
+
+    int oldX = av.getStartRes();
+    int oldY = av.getStartSeq();
+
+    if (evt.getSource() == hscroll)
+    {
+      int x = hscroll.getValue();
+      av.setStartRes(x);
+      av.setEndRes( (x +
+                     (seqPanel.seqCanvas.getWidth() / av.getCharWidth())) - 1);
+    }
+
+    if (evt.getSource() == vscroll)
+    {
+      int offy = vscroll.getValue();
+
+      if (av.getWrapAlignment())
+      {
+        if (offy > -1)
+        {
+          int rowSize = seqPanel.seqCanvas.getWrappedCanvasWidth(seqPanel.
+              seqCanvas.getWidth());
+          av.setStartRes(offy * rowSize);
+          av.setEndRes( (offy + 1) * rowSize);
+        }
+        else
+        {
+          //This is only called if file loaded is a jar file that
+          //was wrapped when saved and user has wrap alignment true
+          //as preference setting
+          SwingUtilities.invokeLater(new Runnable()
+          {
+            public void run()
+            {
+              setScrollValues(av.getStartRes(), av.getStartSeq());
+            }
+          });
+        }
+      }
+      else
+      {
+        av.setStartSeq(offy);
+        av.setEndSeq(offy +
+                     (seqPanel.seqCanvas.getHeight() / av.getCharHeight()));
+      }
+    }
+
+    if (overviewPanel != null)
+    {
+      overviewPanel.setBoxPosition();
+    }
+
+    int scrollX = av.startRes - oldX;
+    int scrollY = av.startSeq - oldY;
+
+    if (av.getWrapAlignment() || !fastPaint)
+    {
+      repaint();
+    }
+    else
+    {
+      // Make sure we're not trying to draw a panel
+      // larger than the visible window
+      if (scrollX > av.endRes - av.startRes)
+      {
+        scrollX = av.endRes - av.startRes;
+      }
+      else if (scrollX < av.startRes - av.endRes)
+      {
+        scrollX = av.startRes - av.endRes;
+      }
+
+      if (scrollX != 0 || scrollY != 0)
+      {
+        idPanel.idCanvas.fastPaint(scrollY);
+        seqPanel.seqCanvas.fastPaint(scrollX,
+                                     scrollY);
+        scalePanel.repaint();
+
+        if (av.getShowAnnotation())
+        {
+          annotationPanel.fastPaint(scrollX);
+        }
+      }
+    }
+  }
+
+  public void paintAlignment(boolean updateOverview)
+  {
+    repaint();
+
+    if(updateOverview)
+    {
+      jalview.structure.StructureSelectionManager.getStructureSelectionManager()
+          .sequenceColoursChanged(this);
+
+      if (overviewPanel != null)
+      {
+        overviewPanel.updateOverviewImage();
+      }
+    }
+  }
+
+  /**
+   * DOCUMENT ME!
+   *
+   * @param g DOCUMENT ME!
+   */
+  public void paintComponent(Graphics g)
+  {
+    invalidate();
+
+    Dimension d = idPanel.idCanvas.getPreferredSize();
+    idPanelHolder.setPreferredSize(d);
+    hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
+    validate();
+
+    if (av.getWrapAlignment())
+    {
+      int maxwidth = av.alignment.getWidth();
+
+      if (av.hasHiddenColumns)
+      {
+        maxwidth = av.getColumnSelection().findColumnPosition(maxwidth) - 1;
+      }
+
+      int canvasWidth = seqPanel.seqCanvas.getWrappedCanvasWidth(seqPanel.
+          seqCanvas.getWidth());
+      if (canvasWidth > 0)
+      {
+        int max = maxwidth /
+            seqPanel.seqCanvas.getWrappedCanvasWidth(seqPanel.seqCanvas.
+            getWidth()) +
+            1;
+        vscroll.setMaximum(max);
+        vscroll.setUnitIncrement(1);
+        vscroll.setVisibleAmount(1);
+      }
+    }
+    else
+    {
+      setScrollValues(av.getStartRes(), av.getStartSeq());
+    }
+  }
+
+  /**
+   * DOCUMENT ME!
+   *
+   * @param pg DOCUMENT ME!
+   * @param pf DOCUMENT ME!
+   * @param pi DOCUMENT ME!
+   *
+   * @return DOCUMENT ME!
+   *
+   * @throws PrinterException DOCUMENT ME!
+   */
+  public int print(Graphics pg, PageFormat pf, int pi)
+      throws PrinterException
+  {
+    pg.translate( (int) pf.getImageableX(), (int) pf.getImageableY());
+
+    int pwidth = (int) pf.getImageableWidth();
+    int pheight = (int) pf.getImageableHeight();
+
+    if (av.getWrapAlignment())
+    {
+      return printWrappedAlignment(pg, pwidth, pheight, pi);
+    }
+    else
+    {
+      return printUnwrapped(pg, pwidth, pheight, pi);
+    }
+  }
+
+  /**
+   * DOCUMENT ME!
+   *
+   * @param pg DOCUMENT ME!
+   * @param pwidth DOCUMENT ME!
+   * @param pheight DOCUMENT ME!
+   * @param pi DOCUMENT ME!
+   *
+   * @return DOCUMENT ME!
+   *
+   * @throws PrinterException DOCUMENT ME!
+   */
+  public int printUnwrapped(Graphics pg, int pwidth, int pheight, int pi)
+      throws PrinterException
+  {
+    int idWidth = getVisibleIdWidth();
+    FontMetrics fm = getFontMetrics(av.getFont());
+    int scaleHeight = av.charHeight + fm.getDescent();
+
+    pg.setColor(Color.white);
+    pg.fillRect(0, 0, pwidth, pheight);
+    pg.setFont(av.getFont());
+
+    ////////////////////////////////////
+    /// How many sequences and residues can we fit on a printable page?
+    int totalRes = (pwidth - idWidth) / av.getCharWidth();
+
+    int totalSeq = (int) ( (pheight - scaleHeight) / av.getCharHeight()) -
+        1;
+
+    int pagesWide = (av.getAlignment().getWidth() / totalRes) + 1;
+
+    /////////////////////////////
+    /// Only print these sequences and residues on this page
+    int startRes;
+
+    /////////////////////////////
+    /// Only print these sequences and residues on this page
+    int endRes;
+
+    /////////////////////////////
+    /// Only print these sequences and residues on this page
+    int startSeq;
+
+    /////////////////////////////
+    /// Only print these sequences and residues on this page
+    int endSeq;
+    startRes = (pi % pagesWide) * totalRes;
+    endRes = (startRes + totalRes) - 1;
+
+    if (endRes > (av.getAlignment().getWidth() - 1))
+    {
+      endRes = av.getAlignment().getWidth() - 1;
+    }
+
+    startSeq = (pi / pagesWide) * totalSeq;
+    endSeq = startSeq + totalSeq;
+
+    if (endSeq > av.getAlignment().getHeight())
+    {
+      endSeq = av.getAlignment().getHeight();
+    }
+
+    int pagesHigh = ( (av.alignment.getHeight() / totalSeq) + 1) * pheight;
+
+    if (av.showAnnotation)
+    {
+      pagesHigh += annotationPanel.adjustPanelHeight() + 3;
+    }
+
+    pagesHigh /= pheight;
+
+    if (pi >= (pagesWide * pagesHigh))
+    {
+      return Printable.NO_SUCH_PAGE;
+    }
+
+    //draw Scale
+    pg.translate(idWidth, 0);
+    scalePanel.drawScale(pg, startRes, endRes, pwidth - idWidth, scaleHeight);
+    pg.translate( -idWidth, scaleHeight);
+
+    ////////////////
+    // Draw the ids
+    Color currentColor = null;
+    Color currentTextColor = null;
+
+    pg.setFont(idPanel.idCanvas.idfont);
+
+    SequenceI seq;
+    for (int i = startSeq; i < endSeq; i++)
+    {
+      seq = av.getAlignment().getSequenceAt(i);
+      if ( (av.getSelectionGroup() != null) &&
+          av.getSelectionGroup().getSequences(null).contains(seq))
+      {
+        currentColor = Color.gray;
+        currentTextColor = Color.black;
+      }
+      else
+      {
+        currentColor = av.getSequenceColour(seq);
+        currentTextColor = Color.black;
+      }
+
+      pg.setColor(currentColor);
+      pg.fillRect(0, (i - startSeq) * av.charHeight, idWidth,
+                  av.getCharHeight());
+
+      pg.setColor(currentTextColor);
+
+      int xPos = 0;
+      if (av.rightAlignIds)
+      {
+        fm = pg.getFontMetrics();
+        xPos = idWidth - fm.stringWidth(
+            seq.getDisplayId(av.getShowJVSuffix())
+            ) - 4;
+      }
+
+      pg.drawString(seq.getDisplayId(av.getShowJVSuffix()),
+                    xPos,
+                    ( ( (i - startSeq) * av.charHeight) + av.getCharHeight()) -
+                    (av.getCharHeight() / 5));
+    }
+
+    pg.setFont(av.getFont());
+
+    // draw main sequence panel
+    pg.translate(idWidth, 0);
+    seqPanel.seqCanvas.drawPanel(pg, startRes, endRes, startSeq, endSeq, 0);
+
+    if (av.showAnnotation && (endSeq == av.alignment.getHeight()))
+    {
+      pg.translate( -idWidth - 3, (endSeq - startSeq) * av.charHeight + 3);
+      alabels.drawComponent( (Graphics2D) pg, idWidth);
+      pg.translate(idWidth + 3, 0);
+      annotationPanel.drawComponent( (Graphics2D) pg, startRes, endRes +
+                                    1);
+    }
+
+    return Printable.PAGE_EXISTS;
+  }
+
+  /**
+   * DOCUMENT ME!
+   *
+   * @param pg DOCUMENT ME!
+   * @param pwidth DOCUMENT ME!
+   * @param pheight DOCUMENT ME!
+   * @param pi DOCUMENT ME!
+   *
+   * @return DOCUMENT ME!
+   *
+   * @throws PrinterException DOCUMENT ME!
+   */
+  public int printWrappedAlignment(Graphics pg, int pwidth, int pheight,
+                                   int pi)
+      throws PrinterException
+  {
+
+    int annotationHeight = 0;
+    AnnotationLabels labels = null;
+    if (av.showAnnotation)
+    {
+      annotationHeight = annotationPanel.adjustPanelHeight();
+      labels = new AnnotationLabels(av);
+    }
+
+    int hgap = av.charHeight;
+    if (av.scaleAboveWrapped)
+    {
+      hgap += av.charHeight;
+    }
+
+    int cHeight = av.getAlignment().getHeight() * av.charHeight
+        + hgap
+        + annotationHeight;
+
+    int idWidth = getVisibleIdWidth();
+
+    int maxwidth = av.alignment.getWidth();
+    if (av.hasHiddenColumns)
+    {
+      maxwidth = av.getColumnSelection().findColumnPosition(maxwidth) - 1;
+    }
+
+    int resWidth = seqPanel.seqCanvas.getWrappedCanvasWidth(pwidth -
+        idWidth);
+
+    int totalHeight = cHeight * (maxwidth / resWidth + 1);
+
+    pg.setColor(Color.white);
+    pg.fillRect(0, 0, pwidth, pheight);
+    pg.setFont(av.getFont());
+
+    ////////////////
+    // Draw the ids
+    pg.setColor(Color.black);
+
+    pg.translate(0, -pi * pheight);
+
+    pg.setClip(0, pi * pheight, pwidth, pheight);
+
+    int ypos = hgap;
+
+    do
+    {
+      for (int i = 0; i < av.alignment.getHeight(); i++)
+      {
+        pg.setFont(idPanel.idCanvas.idfont);
+        SequenceI s = av.alignment.getSequenceAt(i);
+        String string = s.getDisplayId(av.getShowJVSuffix());
+        int xPos = 0;
+        if (av.rightAlignIds)
+        {
+          FontMetrics fm = pg.getFontMetrics();
+          xPos = idWidth - fm.stringWidth(string) - 4;
+        }
+        pg.drawString(string, xPos,
+                      ( (i * av.charHeight) + ypos + av.charHeight) -
+                      (av.charHeight / 5));
+      }
+      if (labels != null)
+      {
+        pg.translate( -3,
+                     ypos +
+                     (av.getAlignment().getHeight() * av.charHeight));
+
+        pg.setFont(av.getFont());
+        labels.drawComponent(pg, idWidth);
+        pg.translate( +3,
+                     -ypos -
+                     (av.getAlignment().getHeight() * av.charHeight));
+      }
+
+      ypos += cHeight;
+    }
+    while (ypos < totalHeight);
+
+    pg.translate(idWidth, 0);
+
+    seqPanel.seqCanvas.drawWrappedPanel(pg, pwidth - idWidth, totalHeight, 0);
+
+    if ( (pi * pheight) < totalHeight)
+    {
+      return Printable.PAGE_EXISTS;
+
+    }
+    else
+    {
+      return Printable.NO_SUCH_PAGE;
+    }
+  }
+
+  int getVisibleIdWidth()
+  {
+    return
+        idPanel.getWidth() > 0 ? idPanel.getWidth() :
+        calculateIdWidth().width + 4;
+  }
+
+  void makeAlignmentImage(int type, File file)
+  {
+    int maxwidth = av.alignment.getWidth();
+    if (av.hasHiddenColumns)
+    {
+      maxwidth = av.getColumnSelection().findColumnPosition(maxwidth);
+    }
+
+    int height = ( (av.alignment.getHeight() + 1) * av.charHeight)
+        + scalePanel.getHeight();
+    int width = getVisibleIdWidth() + (maxwidth * av.charWidth);
+
+    if (av.getWrapAlignment())
+    {
+      height = getWrappedHeight();
+      if (System.getProperty("java.awt.headless") != null
+          && System.getProperty("java.awt.headless").equals("true"))
+      {
+        width = alignFrame.getWidth()
+            - vscroll.getPreferredSize().width
+            - alignFrame.getInsets().left
+            - alignFrame.getInsets().right;
+      }
+      else
+      {
+        width = seqPanel.getWidth() + getVisibleIdWidth();
+      }
+
+    }
+    else if (av.getShowAnnotation())
+    {
+      height += annotationPanel.adjustPanelHeight() + 3;
+    }
+
+    try
+    {
+
+      jalview.util.ImageMaker im;
+      if (type == jalview.util.ImageMaker.PNG)
+      {
+        im = new jalview.util.ImageMaker(this,
+                                         jalview.util.ImageMaker.PNG,
+                                         "Create PNG image from alignment",
+                                         width, height, file, null);
+      }
+      else
+      {
+        im = new jalview.util.ImageMaker(this,
+                                         jalview.util.ImageMaker.EPS,
+                                         "Create EPS file from alignment",
+                                         width, height, file,
+                                         alignFrame.getTitle());
+      }
+
+      if (av.getWrapAlignment())
+      {
+        if (im.getGraphics() != null)
+        {
+          printWrappedAlignment(im.getGraphics(), width, height, 0);
+          im.writeImage();
+        }
+      }
+      else
+      {
+        if (im.getGraphics() != null)
+        {
+          printUnwrapped(im.getGraphics(), width, height, 0);
+          im.writeImage();
+        }
+      }
+    }
+    catch (OutOfMemoryError err)
+    {
+      // Be noisy here.
+      System.out.println("########################\n"
+                         + "OUT OF MEMORY " + file + "\n"
+                         + "########################");
+      new OOMWarning("Creating Image for "+file,err);
+      // System.out.println("Create IMAGE: " + err);
+    }
+    catch (Exception ex)
+    {
+      ex.printStackTrace();
+    }
+  }
+
+  /**
+   * DOCUMENT ME!
+   */
+  public void makeEPS(File epsFile)
+  {
+    makeAlignmentImage(jalview.util.ImageMaker.EPS, epsFile);
+  }
+
+  /**
+   * DOCUMENT ME!
+   */
+  public void makePNG(File pngFile)
+  {
+    makeAlignmentImage(jalview.util.ImageMaker.PNG, pngFile);
+  }
+
+  public void makePNGImageMap(File imgMapFile, String imageName)
+  {
+    ///////ONLY WORKS WITH NONE WRAPPED ALIGNMENTS
+    //////////////////////////////////////////////
+    int idWidth = getVisibleIdWidth();
+    FontMetrics fm = getFontMetrics(av.getFont());
+    int scaleHeight = av.charHeight + fm.getDescent();
+
+    // Gen image map
+    //////////////////////////////////
+    if (imgMapFile != null)
+    {
+      try
+      {
+        int s, sSize = av.alignment.getHeight(),
+            res, alwidth = av.alignment.getWidth(), g, gSize, f, fSize, sy;
+        StringBuffer text = new StringBuffer();
+        PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
+        out.println(jalview.io.HTMLOutput.getImageMapHTML());
+        out.println("<img src=\"" + imageName +
+                    "\" border=\"0\" usemap=\"#Map\" >"
+                    + "<map name=\"Map\">");
+
+        for (s = 0; s < sSize; s++)
+        {
+          sy = s * av.charHeight + scaleHeight;
+
+          SequenceI seq = av.alignment.getSequenceAt(s);
+          SequenceFeature[] features = seq.getDatasetSequence().
+              getSequenceFeatures();
+          SequenceGroup[] groups = av.alignment.findAllGroups(seq);
+          for (res = 0; res < alwidth; res++)
+          {
+            text = new StringBuffer();
+            Object obj = null;
+            if (av.alignment.isNucleotide())
+            {
+              obj = ResidueProperties.nucleotideName.get(seq.getCharAt(res) +
+                  "");
+            }
+            else
+            {
+              obj = ResidueProperties.aa2Triplet.get(
+                  seq.getCharAt(res) + "");
+            }
+
+            if (obj == null)
+            {
+              continue;
+            }
+
+            String triplet = obj.toString();
+            int alIndex = seq.findPosition(res);
+            gSize = groups.length;
+            for (g = 0; g < gSize; g++)
+            {
+              if (text.length() < 1)
+              {
+                text.append("<area shape=\"rect\" coords=\""
+                            + (idWidth + res * av.charWidth) + ","
+                            + sy + ","
+                            + (idWidth + (res + 1) * av.charWidth) + ","
+                            + (av.charHeight + sy) + "\""
+                            + " onMouseOver=\"toolTip('"
+                            + alIndex + " " + triplet);
+              }
+
+              if (groups[g].getStartRes() < res && groups[g].getEndRes() > res)
+              {
+                text.append("<br><em>" + groups[g].getName() + "</em>");
+              }
+            }
+
+            if (features != null)
+            {
+              if (text.length() < 1)
+              {
+                text.append("<area shape=\"rect\" coords=\""
+                            + (idWidth + res * av.charWidth) + ","
+                            + sy + ","
+                            + (idWidth + (res + 1) * av.charWidth) + ","
+                            + (av.charHeight + sy) + "\""
+                            + " onMouseOver=\"toolTip('"
+                            + alIndex + " " + triplet);
+              }
+              fSize = features.length;
+              for (f = 0; f < fSize; f++)
+              {
+
+                if ( (features[f].getBegin() <= seq.findPosition(res)) &&
+                    (features[f].getEnd() >= seq.findPosition(res)))
+                {
+                  if (features[f].getType().equals("disulfide bond"))
+                  {
+                    if (features[f].getBegin() == seq.findPosition(res)
+                        || features[f].getEnd() == seq.findPosition(res))
+                    {
+                      text.append("<br>disulfide bond " + features[f].getBegin() +
+                                  ":" +
+                                  features[f].getEnd());
+                    }
+                  }
+                  else
+                  {
+                    text.append("<br>");
+                    text.append(features[f].getType());
+                    if (features[f].getDescription() != null &&
+                        !features[f].
+                        getType().equals(features[f].getDescription()))
+                    {
+                      text.append(" " + features[f].getDescription());
+                    }
+
+                    if (features[f].getValue("status") != null)
+                    {
+                      text.append(" (" + features[f].getValue("status") + ")");
+                    }
+                  }
+                }
+
+              }
+            }
+            if (text.length() > 1)
+            {
+              text.append("')\"; onMouseOut=\"toolTip()\";  href=\"#\">");
+              out.println(text.toString());
+            }
+          }
+        }
+        out.println("</map></body></html>");
+        out.close();
+
+      }
+      catch (Exception ex)
+      {
+        ex.printStackTrace();
+      }
+    } ///////////END OF IMAGE MAP
+
+  }
+
+  int getWrappedHeight()
+  {
+    int seqPanelWidth = seqPanel.seqCanvas.getWidth();
+
+    if (System.getProperty("java.awt.headless") != null
+        && System.getProperty("java.awt.headless").equals("true"))
+    {
+      seqPanelWidth = alignFrame.getWidth()
+          - getVisibleIdWidth()
+          - vscroll.getPreferredSize().width
+          - alignFrame.getInsets().left
+          - alignFrame.getInsets().right;
+    }
+
+    int chunkWidth = seqPanel.seqCanvas.getWrappedCanvasWidth(
+        seqPanelWidth
+        );
+
+    int hgap = av.charHeight;
+    if (av.scaleAboveWrapped)
+    {
+      hgap += av.charHeight;
+    }
+
+    int annotationHeight = 0;
+    if (av.showAnnotation)
+    {
+      annotationHeight = annotationPanel.adjustPanelHeight();
+    }
+
+    int cHeight = av.getAlignment().getHeight() * av.charHeight
+        + hgap
+        + annotationHeight;
+
+    int maxwidth = av.alignment.getWidth();
+    if (av.hasHiddenColumns)
+    {
+      maxwidth = av.getColumnSelection().findColumnPosition(maxwidth) - 1;
+    }
+
+    int height = ( (maxwidth / chunkWidth) + 1) * cHeight;
+
+    return height;
+  }
+}