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