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