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