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