added bugfix todo
[jalview.git] / src / jalview / gui / AlignmentPanel.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer
3  * Copyright (C) 2007 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
18  */
19 package jalview.gui;
20
21 import java.beans.*;
22 import java.io.*;
23
24 import java.awt.*;
25 import java.awt.event.*;
26 import java.awt.print.*;
27 import javax.swing.*;
28
29 import jalview.datamodel.*;
30 import jalview.jbgui.*;
31 import jalview.schemes.*;
32
33 /**
34  * DOCUMENT ME!
35  *
36  * @author $author$
37  * @version $Revision$
38  */
39 public class AlignmentPanel
40     extends GAlignmentPanel implements AdjustmentListener, Printable
41 {
42   public AlignViewport av;
43   OverviewPanel overviewPanel;
44   SeqPanel seqPanel;
45   IdPanel idPanel;
46   IdwidthAdjuster idwidthAdjuster;
47
48   /** DOCUMENT ME!! */
49   public AlignFrame alignFrame;
50   ScalePanel scalePanel;
51   AnnotationPanel annotationPanel;
52   AnnotationLabels alabels;
53
54   // this value is set false when selection area being dragged
55   boolean fastPaint = true;
56   int hextent = 0;
57   int vextent = 0;
58
59   /**
60    * Creates a new AlignmentPanel object.
61    *
62    * @param af DOCUMENT ME!
63    * @param av DOCUMENT ME!
64    */
65   public AlignmentPanel(AlignFrame af, final AlignViewport av)
66   {
67     alignFrame = af;
68     this.av = av;
69     seqPanel = new SeqPanel(av, this);
70     idPanel = new IdPanel(av, this);
71
72     scalePanel = new ScalePanel(av, this);
73
74     idPanelHolder.add(idPanel, BorderLayout.CENTER);
75     idwidthAdjuster = new IdwidthAdjuster(this);
76     idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
77
78     annotationPanel = new AnnotationPanel(this);
79     alabels = new AnnotationLabels(this);
80
81     annotationScroller.setViewportView(annotationPanel);
82     annotationSpaceFillerHolder.add(alabels, BorderLayout.CENTER);
83
84     scalePanelHolder.add(scalePanel, BorderLayout.CENTER);
85     seqPanelHolder.add(seqPanel, BorderLayout.CENTER);
86
87     setScrollValues(0, 0);
88
89     setAnnotationVisible(av.getShowAnnotation());
90
91     hscroll.addAdjustmentListener(this);
92     vscroll.addAdjustmentListener(this);
93
94     final AlignmentPanel ap = this;
95     av.addPropertyChangeListener(new PropertyChangeListener()
96     {
97       public void propertyChange(PropertyChangeEvent evt)
98       {
99         if (evt.getPropertyName().equals("alignment"))
100         {
101           PaintRefresher.Refresh(ap,
102                                  av.getSequenceSetId(),
103                                  true,
104                                  true);
105           alignmentChanged();
106         }
107       }
108     });
109
110     fontChanged();
111     adjustAnnotationHeight();
112
113   }
114
115   public void alignmentChanged()
116   {
117     av.alignmentChanged(this);
118
119     alignFrame.updateEditMenuBar();
120
121     paintAlignment(true);
122
123   }
124
125   /**
126    * DOCUMENT ME!
127    */
128   public void fontChanged()
129   {
130     // set idCanvas bufferedImage to null
131     // to prevent drawing old image
132     FontMetrics fm = getFontMetrics(av.getFont());
133
134     scalePanelHolder.setPreferredSize(new Dimension(10,
135         av.charHeight + fm.getDescent()));
136     idSpaceFillerPanel1.setPreferredSize(new Dimension(10,
137         av.charHeight + fm.getDescent()));
138
139     idPanel.idCanvas.gg = null;
140     seqPanel.seqCanvas.img = null;
141     annotationPanel.adjustPanelHeight();
142
143     Dimension d = calculateIdWidth();
144     d.setSize(d.width + 4, d.height);
145     idPanel.idCanvas.setPreferredSize(d);
146     hscrollFillerPanel.setPreferredSize(d);
147
148     if (overviewPanel != null)
149     {
150       overviewPanel.setBoxPosition();
151     }
152
153     repaint();
154   }
155
156   /**
157    * DOCUMENT ME!
158    *
159    * @return DOCUMENT ME!
160    */
161   public Dimension calculateIdWidth()
162   {
163     Container c = new Container();
164
165     FontMetrics fm = c.getFontMetrics(
166         new Font(av.font.getName(), Font.ITALIC, av.font.getSize()));
167
168     AlignmentI al = av.getAlignment();
169
170     int i = 0;
171     int idWidth = 0;
172     String id;
173
174     while ( (i < al.getHeight()) && (al.getSequenceAt(i) != null))
175     {
176       SequenceI s = al.getSequenceAt(i);
177
178       id = s.getDisplayId(av.getShowJVSuffix());
179
180       if (fm.stringWidth(id) > idWidth)
181       {
182         idWidth = fm.stringWidth(id);
183       }
184
185       i++;
186     }
187
188     // Also check annotation label widths
189     i = 0;
190
191     if (al.getAlignmentAnnotation() != null)
192     {
193       fm = c.getFontMetrics(alabels.getFont());
194
195       while (i < al.getAlignmentAnnotation().length)
196       {
197         String label = al.getAlignmentAnnotation()[i].label;
198
199         if (fm.stringWidth(label) > idWidth)
200         {
201           idWidth = fm.stringWidth(label);
202         }
203
204         i++;
205       }
206     }
207
208     return new Dimension(idWidth, 12);
209   }
210
211   /**
212    * DOCUMENT ME!
213    *
214    * @param results DOCUMENT ME!
215    */
216   public void highlightSearchResults(SearchResults results)
217   {
218     seqPanel.seqCanvas.highlightSearchResults(results);
219
220     // do we need to scroll the panel?
221     if (results != null)
222     {
223       SequenceI seq = results.getResultSequence(0);
224       int seqIndex = av.alignment.findIndex(seq);
225       int start = seq.findIndex(results.getResultStart(0)) - 1;
226       int end = seq.findIndex(results.getResultEnd(0)) - 1;
227
228       if (!av.wrapAlignment)
229       {
230         if ( (av.getStartRes() > end) || (av.getEndRes() < start) ||
231             ( (av.getStartSeq() > seqIndex) || (av.getEndSeq() < seqIndex)))
232         {
233           setScrollValues(start, seqIndex);
234         }
235       }
236       else
237       {
238         scrollToWrappedVisible(start);
239       }
240     }
241
242     paintAlignment(true);
243   }
244
245   void scrollToWrappedVisible(int res)
246   {
247     int cwidth = seqPanel.seqCanvas.getWrappedCanvasWidth(seqPanel.seqCanvas.
248         getWidth());
249     if (res <= av.getStartRes() || res >= (av.getStartRes() + cwidth))
250     {
251       vscroll.setValue(res / cwidth);
252       av.startRes = vscroll.getValue() * cwidth;
253     }
254   }
255
256   /**
257    * DOCUMENT ME!
258    *
259    * @return DOCUMENT ME!
260    */
261   public OverviewPanel getOverviewPanel()
262   {
263     return overviewPanel;
264   }
265
266   /**
267    * DOCUMENT ME!
268    *
269    * @param op DOCUMENT ME!
270    */
271   public void setOverviewPanel(OverviewPanel op)
272   {
273     overviewPanel = op;
274   }
275
276   /**
277    * DOCUMENT ME!
278    *
279    * @param b DOCUMENT ME!
280    */
281   public void setAnnotationVisible(boolean b)
282   {
283     if (!av.wrapAlignment)
284     {
285       annotationSpaceFillerHolder.setVisible(b);
286       annotationScroller.setVisible(b);
287     }
288     repaint();
289   }
290
291   public void adjustAnnotationHeight()
292   {
293     //TODO: display vertical annotation scrollbar if necessary 
294     // this is called after loading new annotation onto alignment
295     if (alignFrame.getHeight() == 0)
296     {
297       System.out.println("NEEDS FIXING");
298     }
299
300     int height = annotationPanel.adjustPanelHeight();
301
302     if (hscroll.isVisible())
303     {
304       height += hscroll.getPreferredSize().height;
305     }
306     if (height > alignFrame.getHeight() / 2)
307     {
308       height = alignFrame.getHeight() / 2;
309     }
310
311     hscroll.addNotify();
312
313     annotationScroller.setPreferredSize(
314         new Dimension(annotationScroller.getWidth(), height));
315
316
317     annotationSpaceFillerHolder.setPreferredSize(new Dimension(
318         annotationSpaceFillerHolder.getWidth(),
319         height));
320     annotationScroller.validate();// repaint();
321     repaint();
322   }
323
324   /**
325    * DOCUMENT ME!
326    *
327    * @param wrap DOCUMENT ME!
328    */
329   public void setWrapAlignment(boolean wrap)
330   {
331     av.startSeq = 0;
332     scalePanelHolder.setVisible(!wrap);
333     hscroll.setVisible(!wrap);
334     idwidthAdjuster.setVisible(!wrap);
335
336     if (wrap)
337     {
338       annotationScroller.setVisible(false);
339       annotationSpaceFillerHolder.setVisible(false);
340     }
341     else if (av.showAnnotation)
342     {
343       annotationScroller.setVisible(true);
344       annotationSpaceFillerHolder.setVisible(true);
345     }
346
347     idSpaceFillerPanel1.setVisible(!wrap);
348
349     repaint();
350   }
351
352   // return value is true if the scroll is valid
353   public boolean scrollUp(boolean up)
354   {
355     if (up)
356     {
357       if (vscroll.getValue() < 1)
358       {
359         return false;
360       }
361
362       fastPaint = false;
363       vscroll.setValue(vscroll.getValue() - 1);
364     }
365     else
366     {
367       if ( (vextent + vscroll.getValue()) >= av.getAlignment().getHeight())
368       {
369         return false;
370       }
371
372       fastPaint = false;
373       vscroll.setValue(vscroll.getValue() + 1);
374     }
375
376     fastPaint = true;
377
378     return true;
379   }
380
381   /**
382    * DOCUMENT ME!
383    *
384    * @param right DOCUMENT ME!
385    *
386    * @return DOCUMENT ME!
387    */
388   public boolean scrollRight(boolean right)
389   {
390     if (!right)
391     {
392       if (hscroll.getValue() < 1)
393       {
394         return false;
395       }
396
397       fastPaint = false;
398       hscroll.setValue(hscroll.getValue() - 1);
399     }
400     else
401     {
402       if ( (hextent + hscroll.getValue()) >= av.getAlignment().getWidth())
403       {
404         return false;
405       }
406
407       fastPaint = false;
408       hscroll.setValue(hscroll.getValue() + 1);
409     }
410
411     fastPaint = true;
412
413     return true;
414   }
415
416   /**
417    * DOCUMENT ME!
418    *
419    * @param x DOCUMENT ME!
420    * @param y DOCUMENT ME!
421    */
422   public void setScrollValues(int x, int y)
423   {
424
425     int width = av.alignment.getWidth();
426     int height = av.alignment.getHeight();
427
428     if (av.hasHiddenColumns)
429     {
430       width = av.getColumnSelection().findColumnPosition(width);
431     }
432
433     av.setEndRes( (x + (seqPanel.seqCanvas.getWidth() / av.charWidth)) - 1);
434
435     hextent = seqPanel.seqCanvas.getWidth() / av.charWidth;
436     vextent = seqPanel.seqCanvas.getHeight() / av.charHeight;
437
438     if (hextent > width)
439     {
440       hextent = width;
441     }
442
443     if (vextent > height)
444     {
445       vextent = height;
446     }
447
448     if ( (hextent + x) > width)
449     {
450       x = width - hextent;
451     }
452
453     if ( (vextent + y) > height)
454     {
455       y = height - vextent;
456     }
457
458     if (y < 0)
459     {
460       y = 0;
461     }
462
463     if (x < 0)
464     {
465       x = 0;
466     }
467
468     hscroll.setValues(x, hextent, 0, width);
469     vscroll.setValues(y, vextent, 0, height);
470   }
471
472   /**
473    * DOCUMENT ME!
474    *
475    * @param evt DOCUMENT ME!
476    */
477   public void adjustmentValueChanged(AdjustmentEvent evt)
478   {
479
480     int oldX = av.getStartRes();
481     int oldY = av.getStartSeq();
482
483     if (evt.getSource() == hscroll)
484     {
485       int x = hscroll.getValue();
486       av.setStartRes(x);
487       av.setEndRes( (x +
488                      (seqPanel.seqCanvas.getWidth() / av.getCharWidth())) - 1);
489     }
490
491     if (evt.getSource() == vscroll)
492     {
493       int offy = vscroll.getValue();
494
495       if (av.getWrapAlignment())
496       {
497         if (offy > -1)
498         {
499           int rowSize = seqPanel.seqCanvas.getWrappedCanvasWidth(seqPanel.
500               seqCanvas.getWidth());
501           av.setStartRes(offy * rowSize);
502           av.setEndRes( (offy + 1) * rowSize);
503         }
504         else
505         {
506           //This is only called if file loaded is a jar file that
507           //was wrapped when saved and user has wrap alignment true
508           //as preference setting
509           SwingUtilities.invokeLater(new Runnable()
510           {
511             public void run()
512             {
513               setScrollValues(av.getStartRes(), av.getStartSeq());
514             }
515           });
516         }
517       }
518       else
519       {
520         av.setStartSeq(offy);
521         av.setEndSeq(offy +
522                      (seqPanel.seqCanvas.getHeight() / av.getCharHeight()));
523       }
524     }
525
526     if (overviewPanel != null)
527     {
528       overviewPanel.setBoxPosition();
529     }
530
531     int scrollX = av.startRes - oldX;
532     int scrollY = av.startSeq - oldY;
533
534     if (av.getWrapAlignment() || !fastPaint)
535     {
536       repaint();
537     }
538     else
539     {
540       // Make sure we're not trying to draw a panel
541       // larger than the visible window
542       if (scrollX > av.endRes - av.startRes)
543       {
544         scrollX = av.endRes - av.startRes;
545       }
546       else if (scrollX < av.startRes - av.endRes)
547       {
548         scrollX = av.startRes - av.endRes;
549       }
550
551       if (scrollX != 0 || scrollY != 0)
552       {
553         idPanel.idCanvas.fastPaint(scrollY);
554         seqPanel.seqCanvas.fastPaint(scrollX,
555                                      scrollY);
556         scalePanel.repaint();
557
558         if (av.getShowAnnotation())
559         {
560           annotationPanel.fastPaint(scrollX);
561         }
562       }
563     }
564   }
565
566   public void paintAlignment(boolean updateOverview)
567   {
568     repaint();
569
570     if(updateOverview)
571     {
572       jalview.structure.StructureSelectionManager.getStructureSelectionManager()
573           .sequenceColoursChanged(this);
574
575       if (overviewPanel != null)
576       {
577         overviewPanel.updateOverviewImage();
578       }
579     }
580   }
581
582   /**
583    * DOCUMENT ME!
584    *
585    * @param g DOCUMENT ME!
586    */
587   public void paintComponent(Graphics g)
588   {
589     invalidate();
590
591     Dimension d = idPanel.idCanvas.getPreferredSize();
592     idPanelHolder.setPreferredSize(d);
593     hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
594     validate();
595
596     if (av.getWrapAlignment())
597     {
598       int maxwidth = av.alignment.getWidth();
599
600       if (av.hasHiddenColumns)
601       {
602         maxwidth = av.getColumnSelection().findColumnPosition(maxwidth) - 1;
603       }
604
605       int canvasWidth = seqPanel.seqCanvas.getWrappedCanvasWidth(seqPanel.
606           seqCanvas.getWidth());
607       if (canvasWidth > 0)
608       {
609         int max = maxwidth /
610             seqPanel.seqCanvas.getWrappedCanvasWidth(seqPanel.seqCanvas.
611             getWidth()) +
612             1;
613         vscroll.setMaximum(max);
614         vscroll.setUnitIncrement(1);
615         vscroll.setVisibleAmount(1);
616       }
617     }
618     else
619     {
620       setScrollValues(av.getStartRes(), av.getStartSeq());
621     }
622   }
623
624   /**
625    * DOCUMENT ME!
626    *
627    * @param pg DOCUMENT ME!
628    * @param pf DOCUMENT ME!
629    * @param pi DOCUMENT ME!
630    *
631    * @return DOCUMENT ME!
632    *
633    * @throws PrinterException DOCUMENT ME!
634    */
635   public int print(Graphics pg, PageFormat pf, int pi)
636       throws PrinterException
637   {
638     pg.translate( (int) pf.getImageableX(), (int) pf.getImageableY());
639
640     int pwidth = (int) pf.getImageableWidth();
641     int pheight = (int) pf.getImageableHeight();
642
643     if (av.getWrapAlignment())
644     {
645       return printWrappedAlignment(pg, pwidth, pheight, pi);
646     }
647     else
648     {
649       return printUnwrapped(pg, pwidth, pheight, pi);
650     }
651   }
652
653   /**
654    * DOCUMENT ME!
655    *
656    * @param pg DOCUMENT ME!
657    * @param pwidth DOCUMENT ME!
658    * @param pheight DOCUMENT ME!
659    * @param pi DOCUMENT ME!
660    *
661    * @return DOCUMENT ME!
662    *
663    * @throws PrinterException DOCUMENT ME!
664    */
665   public int printUnwrapped(Graphics pg, int pwidth, int pheight, int pi)
666       throws PrinterException
667   {
668     int idWidth = getVisibleIdWidth();
669     FontMetrics fm = getFontMetrics(av.getFont());
670     int scaleHeight = av.charHeight + fm.getDescent();
671
672     pg.setColor(Color.white);
673     pg.fillRect(0, 0, pwidth, pheight);
674     pg.setFont(av.getFont());
675
676     ////////////////////////////////////
677     /// How many sequences and residues can we fit on a printable page?
678     int totalRes = (pwidth - idWidth) / av.getCharWidth();
679
680     int totalSeq = (int) ( (pheight - scaleHeight) / av.getCharHeight()) -
681         1;
682
683     int pagesWide = (av.getAlignment().getWidth() / totalRes) + 1;
684
685     /////////////////////////////
686     /// Only print these sequences and residues on this page
687     int startRes;
688
689     /////////////////////////////
690     /// Only print these sequences and residues on this page
691     int endRes;
692
693     /////////////////////////////
694     /// Only print these sequences and residues on this page
695     int startSeq;
696
697     /////////////////////////////
698     /// Only print these sequences and residues on this page
699     int endSeq;
700     startRes = (pi % pagesWide) * totalRes;
701     endRes = (startRes + totalRes) - 1;
702
703     if (endRes > (av.getAlignment().getWidth() - 1))
704     {
705       endRes = av.getAlignment().getWidth() - 1;
706     }
707
708     startSeq = (pi / pagesWide) * totalSeq;
709     endSeq = startSeq + totalSeq;
710
711     if (endSeq > av.getAlignment().getHeight())
712     {
713       endSeq = av.getAlignment().getHeight();
714     }
715
716     int pagesHigh = ( (av.alignment.getHeight() / totalSeq) + 1) * pheight;
717
718     if (av.showAnnotation)
719     {
720       pagesHigh += annotationPanel.adjustPanelHeight() + 3;
721     }
722
723     pagesHigh /= pheight;
724
725     if (pi >= (pagesWide * pagesHigh))
726     {
727       return Printable.NO_SUCH_PAGE;
728     }
729
730     //draw Scale
731     pg.translate(idWidth, 0);
732     scalePanel.drawScale(pg, startRes, endRes, pwidth - idWidth, scaleHeight);
733     pg.translate( -idWidth, scaleHeight);
734
735     ////////////////
736     // Draw the ids
737     Color currentColor = null;
738     Color currentTextColor = null;
739
740     pg.setFont(idPanel.idCanvas.idfont);
741
742     SequenceI seq;
743     for (int i = startSeq; i < endSeq; i++)
744     {
745       seq = av.getAlignment().getSequenceAt(i);
746       if ( (av.getSelectionGroup() != null) &&
747           av.getSelectionGroup().getSequences(null).contains(seq))
748       {
749         currentColor = Color.gray;
750         currentTextColor = Color.black;
751       }
752       else
753       {
754         currentColor = av.getSequenceColour(seq);
755         currentTextColor = Color.black;
756       }
757
758       pg.setColor(currentColor);
759       pg.fillRect(0, (i - startSeq) * av.charHeight, idWidth,
760                   av.getCharHeight());
761
762       pg.setColor(currentTextColor);
763
764       int xPos = 0;
765       if (av.rightAlignIds)
766       {
767         fm = pg.getFontMetrics();
768         xPos = idWidth - fm.stringWidth(
769             seq.getDisplayId(av.getShowJVSuffix())
770             ) - 4;
771       }
772
773       pg.drawString(seq.getDisplayId(av.getShowJVSuffix()),
774                     xPos,
775                     ( ( (i - startSeq) * av.charHeight) + av.getCharHeight()) -
776                     (av.getCharHeight() / 5));
777     }
778
779     pg.setFont(av.getFont());
780
781     // draw main sequence panel
782     pg.translate(idWidth, 0);
783     seqPanel.seqCanvas.drawPanel(pg, startRes, endRes, startSeq, endSeq, 0);
784
785     if (av.showAnnotation && (endSeq == av.alignment.getHeight()))
786     {
787       pg.translate( -idWidth - 3, (endSeq - startSeq) * av.charHeight + 3);
788       alabels.drawComponent( (Graphics2D) pg, idWidth);
789       pg.translate(idWidth + 3, 0);
790       annotationPanel.drawComponent( (Graphics2D) pg, startRes, endRes +
791                                     1);
792     }
793
794     return Printable.PAGE_EXISTS;
795   }
796
797   /**
798    * DOCUMENT ME!
799    *
800    * @param pg DOCUMENT ME!
801    * @param pwidth DOCUMENT ME!
802    * @param pheight DOCUMENT ME!
803    * @param pi DOCUMENT ME!
804    *
805    * @return DOCUMENT ME!
806    *
807    * @throws PrinterException DOCUMENT ME!
808    */
809   public int printWrappedAlignment(Graphics pg, int pwidth, int pheight,
810                                    int pi)
811       throws PrinterException
812   {
813
814     int annotationHeight = 0;
815     AnnotationLabels labels = null;
816     if (av.showAnnotation)
817     {
818       annotationHeight = annotationPanel.adjustPanelHeight();
819       labels = new AnnotationLabels(av);
820     }
821
822     int hgap = av.charHeight;
823     if (av.scaleAboveWrapped)
824     {
825       hgap += av.charHeight;
826     }
827
828     int cHeight = av.getAlignment().getHeight() * av.charHeight
829         + hgap
830         + annotationHeight;
831
832     int idWidth = getVisibleIdWidth();
833
834     int maxwidth = av.alignment.getWidth();
835     if (av.hasHiddenColumns)
836     {
837       maxwidth = av.getColumnSelection().findColumnPosition(maxwidth) - 1;
838     }
839
840     int resWidth = seqPanel.seqCanvas.getWrappedCanvasWidth(pwidth -
841         idWidth);
842
843     int totalHeight = cHeight * (maxwidth / resWidth + 1);
844
845     pg.setColor(Color.white);
846     pg.fillRect(0, 0, pwidth, pheight);
847     pg.setFont(av.getFont());
848
849     ////////////////
850     // Draw the ids
851     pg.setColor(Color.black);
852
853     pg.translate(0, -pi * pheight);
854
855     pg.setClip(0, pi * pheight, pwidth, pheight);
856
857     int ypos = hgap;
858
859     do
860     {
861       for (int i = 0; i < av.alignment.getHeight(); i++)
862       {
863         pg.setFont(idPanel.idCanvas.idfont);
864         SequenceI s = av.alignment.getSequenceAt(i);
865         String string = s.getDisplayId(av.getShowJVSuffix());
866         int xPos = 0;
867         if (av.rightAlignIds)
868         {
869           FontMetrics fm = pg.getFontMetrics();
870           xPos = idWidth - fm.stringWidth(string) - 4;
871         }
872         pg.drawString(string, xPos,
873                       ( (i * av.charHeight) + ypos + av.charHeight) -
874                       (av.charHeight / 5));
875       }
876       if (labels != null)
877       {
878         pg.translate( -3,
879                      ypos +
880                      (av.getAlignment().getHeight() * av.charHeight));
881
882         pg.setFont(av.getFont());
883         labels.drawComponent(pg, idWidth);
884         pg.translate( +3,
885                      -ypos -
886                      (av.getAlignment().getHeight() * av.charHeight));
887       }
888
889       ypos += cHeight;
890     }
891     while (ypos < totalHeight);
892
893     pg.translate(idWidth, 0);
894
895     seqPanel.seqCanvas.drawWrappedPanel(pg, pwidth - idWidth, totalHeight, 0);
896
897     if ( (pi * pheight) < totalHeight)
898     {
899       return Printable.PAGE_EXISTS;
900
901     }
902     else
903     {
904       return Printable.NO_SUCH_PAGE;
905     }
906   }
907
908   int getVisibleIdWidth()
909   {
910     return
911         idPanel.getWidth() > 0 ? idPanel.getWidth() :
912         calculateIdWidth().width + 4;
913   }
914
915   void makeAlignmentImage(int type, File file)
916   {
917     int maxwidth = av.alignment.getWidth();
918     if (av.hasHiddenColumns)
919     {
920       maxwidth = av.getColumnSelection().findColumnPosition(maxwidth);
921     }
922
923     int height = ( (av.alignment.getHeight() + 1) * av.charHeight)
924         + scalePanel.getHeight();
925     int width = getVisibleIdWidth() + (maxwidth * av.charWidth);
926
927     if (av.getWrapAlignment())
928     {
929       height = getWrappedHeight();
930       if (System.getProperty("java.awt.headless") != null
931           && System.getProperty("java.awt.headless").equals("true"))
932       {
933         width = alignFrame.getWidth()
934             - vscroll.getPreferredSize().width
935             - alignFrame.getInsets().left
936             - alignFrame.getInsets().right;
937       }
938       else
939       {
940         width = seqPanel.getWidth() + getVisibleIdWidth();
941       }
942
943     }
944     else if (av.getShowAnnotation())
945     {
946       height += annotationPanel.adjustPanelHeight() + 3;
947     }
948
949     try
950     {
951
952       jalview.util.ImageMaker im;
953       if (type == jalview.util.ImageMaker.PNG)
954       {
955         im = new jalview.util.ImageMaker(this,
956                                          jalview.util.ImageMaker.PNG,
957                                          "Create PNG image from alignment",
958                                          width, height, file, null);
959       }
960       else
961       {
962         im = new jalview.util.ImageMaker(this,
963                                          jalview.util.ImageMaker.EPS,
964                                          "Create EPS file from alignment",
965                                          width, height, file,
966                                          alignFrame.getTitle());
967       }
968
969       if (av.getWrapAlignment())
970       {
971         if (im.getGraphics() != null)
972         {
973           printWrappedAlignment(im.getGraphics(), width, height, 0);
974           im.writeImage();
975         }
976       }
977       else
978       {
979         if (im.getGraphics() != null)
980         {
981           printUnwrapped(im.getGraphics(), width, height, 0);
982           im.writeImage();
983         }
984       }
985     }
986     catch (OutOfMemoryError err)
987     {
988       System.out.println("########################\n"
989                          + "OUT OF MEMORY " + file + "\n"
990                          + "########################");
991
992       JOptionPane.showInternalMessageDialog(Desktop.desktop,
993                                             "Out of Memory Creating Image!!"
994                                             +
995                                             "\nSee help files for increasing Java Virtual Machine memory."
996                                             , "Out of memory",
997                                             JOptionPane.WARNING_MESSAGE);
998       System.out.println("Create IMAGE: " + err);
999       System.gc();
1000
1001     }
1002     catch (Exception ex)
1003     {
1004       ex.printStackTrace();
1005     }
1006   }
1007
1008   /**
1009    * DOCUMENT ME!
1010    */
1011   public void makeEPS(File epsFile)
1012   {
1013     makeAlignmentImage(jalview.util.ImageMaker.EPS, epsFile);
1014   }
1015
1016   /**
1017    * DOCUMENT ME!
1018    */
1019   public void makePNG(File pngFile)
1020   {
1021     makeAlignmentImage(jalview.util.ImageMaker.PNG, pngFile);
1022   }
1023
1024   public void makePNGImageMap(File imgMapFile, String imageName)
1025   {
1026     ///////ONLY WORKS WITH NONE WRAPPED ALIGNMENTS
1027     //////////////////////////////////////////////
1028     int idWidth = getVisibleIdWidth();
1029     FontMetrics fm = getFontMetrics(av.getFont());
1030     int scaleHeight = av.charHeight + fm.getDescent();
1031
1032     // Gen image map
1033     //////////////////////////////////
1034     if (imgMapFile != null)
1035     {
1036       try
1037       {
1038         int s, sSize = av.alignment.getHeight(),
1039             res, alwidth = av.alignment.getWidth(), g, gSize, f, fSize, sy;
1040         StringBuffer text = new StringBuffer();
1041         PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1042         out.println(jalview.io.HTMLOutput.getImageMapHTML());
1043         out.println("<img src=\"" + imageName +
1044                     "\" border=\"0\" usemap=\"#Map\" >"
1045                     + "<map name=\"Map\">");
1046
1047         for (s = 0; s < sSize; s++)
1048         {
1049           sy = s * av.charHeight + scaleHeight;
1050
1051           SequenceI seq = av.alignment.getSequenceAt(s);
1052           SequenceFeature[] features = seq.getDatasetSequence().
1053               getSequenceFeatures();
1054           SequenceGroup[] groups = av.alignment.findAllGroups(seq);
1055           for (res = 0; res < alwidth; res++)
1056           {
1057             text = new StringBuffer();
1058             Object obj = null;
1059             if (av.alignment.isNucleotide())
1060             {
1061               obj = ResidueProperties.nucleotideName.get(seq.getCharAt(res) +
1062                   "");
1063             }
1064             else
1065             {
1066               obj = ResidueProperties.aa2Triplet.get(
1067                   seq.getCharAt(res) + "");
1068             }
1069
1070             if (obj == null)
1071             {
1072               continue;
1073             }
1074
1075             String triplet = obj.toString();
1076             int alIndex = seq.findPosition(res);
1077             gSize = groups.length;
1078             for (g = 0; g < gSize; g++)
1079             {
1080               if (text.length() < 1)
1081               {
1082                 text.append("<area shape=\"rect\" coords=\""
1083                             + (idWidth + res * av.charWidth) + ","
1084                             + sy + ","
1085                             + (idWidth + (res + 1) * av.charWidth) + ","
1086                             + (av.charHeight + sy) + "\""
1087                             + " onMouseOver=\"toolTip('"
1088                             + alIndex + " " + triplet);
1089               }
1090
1091               if (groups[g].getStartRes() < res && groups[g].getEndRes() > res)
1092               {
1093                 text.append("<br><em>" + groups[g].getName() + "</em>");
1094               }
1095             }
1096
1097             if (features != null)
1098             {
1099               if (text.length() < 1)
1100               {
1101                 text.append("<area shape=\"rect\" coords=\""
1102                             + (idWidth + res * av.charWidth) + ","
1103                             + sy + ","
1104                             + (idWidth + (res + 1) * av.charWidth) + ","
1105                             + (av.charHeight + sy) + "\""
1106                             + " onMouseOver=\"toolTip('"
1107                             + alIndex + " " + triplet);
1108               }
1109               fSize = features.length;
1110               for (f = 0; f < fSize; f++)
1111               {
1112
1113                 if ( (features[f].getBegin() <= seq.findPosition(res)) &&
1114                     (features[f].getEnd() >= seq.findPosition(res)))
1115                 {
1116                   if (features[f].getType().equals("disulfide bond"))
1117                   {
1118                     if (features[f].getBegin() == seq.findPosition(res)
1119                         || features[f].getEnd() == seq.findPosition(res))
1120                     {
1121                       text.append("<br>disulfide bond " + features[f].getBegin() +
1122                                   ":" +
1123                                   features[f].getEnd());
1124                     }
1125                   }
1126                   else
1127                   {
1128                     text.append("<br>");
1129                     text.append(features[f].getType());
1130                     if (features[f].getDescription() != null &&
1131                         !features[f].
1132                         getType().equals(features[f].getDescription()))
1133                     {
1134                       text.append(" " + features[f].getDescription());
1135                     }
1136
1137                     if (features[f].getValue("status") != null)
1138                     {
1139                       text.append(" (" + features[f].getValue("status") + ")");
1140                     }
1141                   }
1142                 }
1143
1144               }
1145             }
1146             if (text.length() > 1)
1147             {
1148               text.append("')\"; onMouseOut=\"toolTip()\";  href=\"#\">");
1149               out.println(text.toString());
1150             }
1151           }
1152         }
1153         out.println("</map></body></html>");
1154         out.close();
1155
1156       }
1157       catch (Exception ex)
1158       {
1159         ex.printStackTrace();
1160       }
1161     } ///////////END OF IMAGE MAP
1162
1163   }
1164
1165   int getWrappedHeight()
1166   {
1167     int seqPanelWidth = seqPanel.seqCanvas.getWidth();
1168
1169     if (System.getProperty("java.awt.headless") != null
1170         && System.getProperty("java.awt.headless").equals("true"))
1171     {
1172       seqPanelWidth = alignFrame.getWidth()
1173           - getVisibleIdWidth()
1174           - vscroll.getPreferredSize().width
1175           - alignFrame.getInsets().left
1176           - alignFrame.getInsets().right;
1177     }
1178
1179     int chunkWidth = seqPanel.seqCanvas.getWrappedCanvasWidth(
1180         seqPanelWidth
1181         );
1182
1183     int hgap = av.charHeight;
1184     if (av.scaleAboveWrapped)
1185     {
1186       hgap += av.charHeight;
1187     }
1188
1189     int annotationHeight = 0;
1190     if (av.showAnnotation)
1191     {
1192       annotationHeight = annotationPanel.adjustPanelHeight();
1193     }
1194
1195     int cHeight = av.getAlignment().getHeight() * av.charHeight
1196         + hgap
1197         + annotationHeight;
1198
1199     int maxwidth = av.alignment.getWidth();
1200     if (av.hasHiddenColumns)
1201     {
1202       maxwidth = av.getColumnSelection().findColumnPosition(maxwidth) - 1;
1203     }
1204
1205     int height = ( (maxwidth / chunkWidth) + 1) * cHeight;
1206
1207     return height;
1208   }
1209 }