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