tidy imports
[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       pg.translate(-idWidth - 3, (endSeq - startSeq) * av.charHeight + 3);
924       alabels.drawComponent((Graphics2D) pg, idWidth);
925       pg.translate(idWidth + 3, 0);
926       annotationPanel.renderer.drawComponent(annotationPanel, av, (Graphics2D) pg, -1, startRes, endRes + 1);
927     }
928
929     return Printable.PAGE_EXISTS;
930   }
931
932   /**
933    * DOCUMENT ME!
934    * 
935    * @param pg
936    *          DOCUMENT ME!
937    * @param pwidth
938    *          DOCUMENT ME!
939    * @param pheight
940    *          DOCUMENT ME!
941    * @param pi
942    *          DOCUMENT ME!
943    * 
944    * @return DOCUMENT ME!
945    * 
946    * @throws PrinterException
947    *           DOCUMENT ME!
948    */
949   public int printWrappedAlignment(Graphics pg, int pwidth, int pheight,
950           int pi) throws PrinterException
951   {
952
953     int annotationHeight = 0;
954     AnnotationLabels labels = null;
955     if (av.showAnnotation)
956     {
957       annotationHeight = annotationPanel.adjustPanelHeight();
958       labels = new AnnotationLabels(av);
959     }
960
961     int hgap = av.charHeight;
962     if (av.scaleAboveWrapped)
963     {
964       hgap += av.charHeight;
965     }
966
967     int cHeight = av.getAlignment().getHeight() * av.charHeight + hgap
968             + annotationHeight;
969
970     int idWidth = getVisibleIdWidth(false);
971
972     int maxwidth = av.getAlignment().getWidth();
973     if (av.hasHiddenColumns())
974     {
975       maxwidth = av.getColumnSelection().findColumnPosition(maxwidth) - 1;
976     }
977
978     int resWidth = seqPanel.seqCanvas.getWrappedCanvasWidth(pwidth
979             - idWidth);
980
981     int totalHeight = cHeight * (maxwidth / resWidth + 1);
982
983     pg.setColor(Color.white);
984     pg.fillRect(0, 0, pwidth, pheight);
985     pg.setFont(av.getFont());
986
987     // //////////////
988     // Draw the ids
989     pg.setColor(Color.black);
990
991     pg.translate(0, -pi * pheight);
992
993     pg.setClip(0, pi * pheight, pwidth, pheight);
994
995     int ypos = hgap;
996
997     do
998     {
999       for (int i = 0; i < av.getAlignment().getHeight(); i++)
1000       {
1001         pg.setFont(idPanel.idCanvas.idfont);
1002         SequenceI s = av.getAlignment().getSequenceAt(i);
1003         String string = s.getDisplayId(av.getShowJVSuffix());
1004         int xPos = 0;
1005         if (av.rightAlignIds)
1006         {
1007           FontMetrics fm = pg.getFontMetrics();
1008           xPos = idWidth - fm.stringWidth(string) - 4;
1009         }
1010         pg.drawString(string, xPos,
1011                 ((i * av.charHeight) + ypos + av.charHeight)
1012                         - (av.charHeight / 5));
1013       }
1014       if (labels != null)
1015       {
1016         pg.translate(-3, ypos
1017                 + (av.getAlignment().getHeight() * av.charHeight));
1018
1019         pg.setFont(av.getFont());
1020         labels.drawComponent(pg, idWidth);
1021         pg.translate(+3, -ypos
1022                 - (av.getAlignment().getHeight() * av.charHeight));
1023       }
1024
1025       ypos += cHeight;
1026     } while (ypos < totalHeight);
1027
1028     pg.translate(idWidth, 0);
1029
1030     seqPanel.seqCanvas.drawWrappedPanel(pg, pwidth - idWidth, totalHeight,
1031             0);
1032
1033     if ((pi * pheight) < totalHeight)
1034     {
1035       return Printable.PAGE_EXISTS;
1036
1037     }
1038     else
1039     {
1040       return Printable.NO_SUCH_PAGE;
1041     }
1042   }
1043   /**
1044    * get current sequence ID panel width, or nominal value if panel were to be displayed using default settings
1045    * @return
1046    */
1047   int getVisibleIdWidth()
1048   {
1049     return getVisibleIdWidth(true);
1050   }
1051
1052   /**
1053    * get current sequence ID panel width, or nominal value if panel were to be displayed using default settings
1054    * @param onscreen indicate if the Id width for onscreen or offscreen display should be returned
1055    * @return
1056    */
1057   int getVisibleIdWidth(boolean onscreen)
1058   {
1059     // see if rendering offscreen - check preferences and calc width accordingly
1060     if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1061     {
1062       return calculateIdWidth(-1).width+4;
1063     }
1064     Integer idwidth=null;
1065     if (onscreen || (idwidth=Cache.getIntegerProperty("FIGURE_FIXEDIDWIDTH"))==null) {
1066       return (idPanel.getWidth() > 0 ? idPanel.getWidth()
1067             : calculateIdWidth().width + 4);
1068     }
1069     return idwidth.intValue()+4;
1070   }
1071
1072   void makeAlignmentImage(int type, File file)
1073   {
1074     int maxwidth = av.getAlignment().getWidth();
1075     if (av.hasHiddenColumns())
1076     {
1077       maxwidth = av.getColumnSelection().findColumnPosition(maxwidth);
1078     }
1079
1080     int height = ((av.getAlignment().getHeight() + 1) * av.charHeight)
1081             + scalePanel.getHeight();
1082     int width = getVisibleIdWidth(false) + (maxwidth * av.charWidth);
1083
1084     if (av.getWrapAlignment())
1085     {
1086       height = getWrappedHeight();
1087       if (System.getProperty("java.awt.headless") != null
1088               && System.getProperty("java.awt.headless").equals("true"))
1089       {
1090         // need to obtain default alignment width and then add in any additional allowance for id margin
1091         // this duplicates the calculation in getWrappedHeight but adjusts for offscreen idWith
1092         width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1093                 - alignFrame.getInsets().left
1094                 - alignFrame.getInsets().right
1095                 - getVisibleIdWidth()+getVisibleIdWidth(false);
1096       }
1097       else
1098       {
1099         width = seqPanel.getWidth() + getVisibleIdWidth(false);
1100       }
1101
1102     }
1103     else if (av.getShowAnnotation())
1104     {
1105       height += annotationPanel.adjustPanelHeight() + 3;
1106     }
1107
1108     try
1109     {
1110
1111       jalview.util.ImageMaker im;
1112       if (type == jalview.util.ImageMaker.PNG)
1113       {
1114         im = new jalview.util.ImageMaker(this, jalview.util.ImageMaker.PNG,
1115                 "Create PNG image from alignment", width, height, file,
1116                 null);
1117       }
1118       else
1119       {
1120         im = new jalview.util.ImageMaker(this, jalview.util.ImageMaker.EPS,
1121                 "Create EPS file from alignment", width, height, file,
1122                 alignFrame.getTitle());
1123       }
1124
1125       if (av.getWrapAlignment())
1126       {
1127         if (im.getGraphics() != null)
1128         {
1129           printWrappedAlignment(im.getGraphics(), width, height, 0);
1130           im.writeImage();
1131         }
1132       }
1133       else
1134       {
1135         if (im.getGraphics() != null)
1136         {
1137           printUnwrapped(im.getGraphics(), width, height, 0);
1138           im.writeImage();
1139         }
1140       }
1141     } catch (OutOfMemoryError err)
1142     {
1143       // Be noisy here.
1144       System.out.println("########################\n" + "OUT OF MEMORY "
1145               + file + "\n" + "########################");
1146       new OOMWarning("Creating Image for " + file, err);
1147       // System.out.println("Create IMAGE: " + err);
1148     } catch (Exception ex)
1149     {
1150       ex.printStackTrace();
1151     }
1152   }
1153
1154   /**
1155    * DOCUMENT ME!
1156    */
1157   public void makeEPS(File epsFile)
1158   {
1159     makeAlignmentImage(jalview.util.ImageMaker.EPS, epsFile);
1160   }
1161
1162   /**
1163    * DOCUMENT ME!
1164    */
1165   public void makePNG(File pngFile)
1166   {
1167     makeAlignmentImage(jalview.util.ImageMaker.PNG, pngFile);
1168   }
1169
1170   public void makePNGImageMap(File imgMapFile, String imageName)
1171   {
1172     // /////ONLY WORKS WITH NONE WRAPPED ALIGNMENTS
1173     // ////////////////////////////////////////////
1174     int idWidth = getVisibleIdWidth(false);
1175     FontMetrics fm = getFontMetrics(av.getFont());
1176     int scaleHeight = av.charHeight + fm.getDescent();
1177
1178     // Gen image map
1179     // ////////////////////////////////
1180     if (imgMapFile != null)
1181     {
1182       try
1183       {
1184         int s, sSize = av.getAlignment().getHeight(), res, alwidth = av.getAlignment()
1185                 .getWidth(), g, gSize, f, fSize, sy;
1186         StringBuffer text = new StringBuffer();
1187         PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1188         out.println(jalview.io.HTMLOutput.getImageMapHTML());
1189         out.println("<img src=\"" + imageName
1190                 + "\" border=\"0\" usemap=\"#Map\" >"
1191                 + "<map name=\"Map\">");
1192
1193         for (s = 0; s < sSize; s++)
1194         {
1195           sy = s * av.charHeight + scaleHeight;
1196
1197           SequenceI seq = av.getAlignment().getSequenceAt(s);
1198           SequenceFeature[] features = seq.getDatasetSequence()
1199                   .getSequenceFeatures();
1200           SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1201           for (res = 0; res < alwidth; res++)
1202           {
1203             text = new StringBuffer();
1204             Object obj = null;
1205             if (av.getAlignment().isNucleotide())
1206             {
1207               obj = ResidueProperties.nucleotideName.get(seq.getCharAt(res)
1208                       + "");
1209             }
1210             else
1211             {
1212               obj = ResidueProperties.aa2Triplet.get(seq.getCharAt(res)
1213                       + "");
1214             }
1215
1216             if (obj == null)
1217             {
1218               continue;
1219             }
1220
1221             String triplet = obj.toString();
1222             int alIndex = seq.findPosition(res);
1223             gSize = groups.length;
1224             for (g = 0; g < gSize; g++)
1225             {
1226               if (text.length() < 1)
1227               {
1228                 text.append("<area shape=\"rect\" coords=\""
1229                         + (idWidth + res * av.charWidth) + "," + sy + ","
1230                         + (idWidth + (res + 1) * av.charWidth) + ","
1231                         + (av.charHeight + sy) + "\""
1232                         + " onMouseOver=\"toolTip('" + alIndex + " "
1233                         + triplet);
1234               }
1235
1236               if (groups[g].getStartRes() < res
1237                       && groups[g].getEndRes() > res)
1238               {
1239                 text.append("<br><em>" + groups[g].getName() + "</em>");
1240               }
1241             }
1242
1243             if (features != null)
1244             {
1245               if (text.length() < 1)
1246               {
1247                 text.append("<area shape=\"rect\" coords=\""
1248                         + (idWidth + res * av.charWidth) + "," + sy + ","
1249                         + (idWidth + (res + 1) * av.charWidth) + ","
1250                         + (av.charHeight + sy) + "\""
1251                         + " onMouseOver=\"toolTip('" + alIndex + " "
1252                         + triplet);
1253               }
1254               fSize = features.length;
1255               for (f = 0; f < fSize; f++)
1256               {
1257
1258                 if ((features[f].getBegin() <= seq.findPosition(res))
1259                         && (features[f].getEnd() >= seq.findPosition(res)))
1260                 {
1261                   if (features[f].getType().equals("disulfide bond"))
1262                   {
1263                     if (features[f].getBegin() == seq.findPosition(res)
1264                             || features[f].getEnd() == seq
1265                                     .findPosition(res))
1266                     {
1267                       text.append("<br>disulfide bond "
1268                               + features[f].getBegin() + ":"
1269                               + features[f].getEnd());
1270                     }
1271                   }
1272                   else
1273                   {
1274                     text.append("<br>");
1275                     text.append(features[f].getType());
1276                     if (features[f].getDescription() != null
1277                             && !features[f].getType().equals(
1278                                     features[f].getDescription()))
1279                     {
1280                       text.append(" " + features[f].getDescription());
1281                     }
1282
1283                     if (features[f].getValue("status") != null)
1284                     {
1285                       text.append(" (" + features[f].getValue("status")
1286                               + ")");
1287                     }
1288                   }
1289                 }
1290
1291               }
1292             }
1293             if (text.length() > 1)
1294             {
1295               text.append("')\"; onMouseOut=\"toolTip()\";  href=\"#\">");
1296               out.println(text.toString());
1297             }
1298           }
1299         }
1300         out.println("</map></body></html>");
1301         out.close();
1302
1303       } catch (Exception ex)
1304       {
1305         ex.printStackTrace();
1306       }
1307     } // /////////END OF IMAGE MAP
1308
1309   }
1310
1311   int getWrappedHeight()
1312   {
1313     int seqPanelWidth = seqPanel.seqCanvas.getWidth();
1314
1315     if (System.getProperty("java.awt.headless") != null
1316             && System.getProperty("java.awt.headless").equals("true"))
1317     {
1318       seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1319               - vscroll.getPreferredSize().width
1320               - alignFrame.getInsets().left - alignFrame.getInsets().right;
1321     }
1322
1323     int chunkWidth = seqPanel.seqCanvas
1324             .getWrappedCanvasWidth(seqPanelWidth);
1325
1326     int hgap = av.charHeight;
1327     if (av.scaleAboveWrapped)
1328     {
1329       hgap += av.charHeight;
1330     }
1331
1332     int annotationHeight = 0;
1333     if (av.showAnnotation)
1334     {
1335       annotationHeight = annotationPanel.adjustPanelHeight();
1336     }
1337
1338     int cHeight = av.getAlignment().getHeight() * av.charHeight + hgap
1339             + annotationHeight;
1340
1341     int maxwidth = av.getAlignment().getWidth();
1342     if (av.hasHiddenColumns())
1343     {
1344       maxwidth = av.getColumnSelection().findColumnPosition(maxwidth) - 1;
1345     }
1346
1347     int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1348
1349     return height;
1350   }
1351
1352   /**
1353    * close the panel - deregisters all listeners and nulls any references to
1354    * alignment data.
1355    */
1356   public void closePanel()
1357   {
1358     PaintRefresher.RemoveComponent(seqPanel.seqCanvas);
1359     PaintRefresher.RemoveComponent(idPanel.idCanvas);
1360     PaintRefresher.RemoveComponent(this);
1361     if (av != null)
1362     {
1363       jalview.structure.StructureSelectionManager ssm = av.getStructureSelectionManager();
1364       ssm.removeStructureViewerListener(seqPanel, null);
1365       ssm.removeSelectionListener(seqPanel);
1366       av.setAlignment(null);
1367       av = null;
1368     }
1369     else
1370     {
1371       if (Cache.log.isDebugEnabled())
1372       {
1373         Cache.log.warn("Closing alignment panel which is already closed.");
1374       }
1375     }
1376   }
1377
1378   /**
1379    * hides or shows dynamic annotation rows based on groups and av state flags
1380    */
1381   public void updateAnnotation()
1382   {
1383     updateAnnotation(false);
1384   }
1385
1386   public void updateAnnotation(boolean applyGlobalSettings)
1387   {
1388     // TODO: this should be merged with other annotation update stuff - that
1389     // sits on AlignViewport
1390     boolean updateCalcs = false;
1391     boolean conv = av.isShowGroupConservation();
1392     boolean cons = av.isShowGroupConsensus();
1393     boolean showprf = av.isShowSequenceLogo();
1394     boolean showConsHist = av.isShowConsensusHistogram();
1395     boolean normLogo = av.isNormaliseSequenceLogo();
1396
1397     boolean sortg = true;
1398
1399     // remove old automatic annotation
1400     // add any new annotation
1401
1402     // intersect alignment annotation with alignment groups
1403
1404     AlignmentAnnotation[] aan = av.getAlignment().getAlignmentAnnotation();
1405     Hashtable oldrfs = new Hashtable();
1406     if (aan != null)
1407     {
1408       for (int an = 0; an < aan.length; an++)
1409       {
1410         if (aan[an].autoCalculated && aan[an].groupRef != null)
1411         {
1412           oldrfs.put(aan[an].groupRef, aan[an].groupRef);
1413           av.getAlignment().deleteAnnotation(aan[an]);
1414           aan[an] = null;
1415         }
1416       }
1417     }
1418     if (av.getAlignment().getGroups()!=null)
1419     {
1420       for (SequenceGroup sg:av.getAlignment().getGroups())
1421       {
1422         updateCalcs = false;
1423         if (applyGlobalSettings || !oldrfs.containsKey(sg))
1424         {
1425           // set defaults for this group's conservation/consensus
1426           sg.setshowSequenceLogo(showprf);
1427           sg.setShowConsensusHistogram(showConsHist);
1428           sg.setNormaliseSequenceLogo(normLogo);
1429         }
1430         if (conv)
1431         {
1432           updateCalcs = true;
1433           av.getAlignment().addAnnotation(sg.getConservationRow(), 0);
1434         }
1435         if (cons)
1436         {
1437           updateCalcs = true;
1438           av.getAlignment().addAnnotation(sg.getConsensus(), 0);
1439         }
1440         // refresh the annotation rows
1441         if (updateCalcs)
1442         {
1443           sg.recalcConservation();
1444         }
1445       }
1446     }
1447     oldrfs.clear();
1448     adjustAnnotationHeight();
1449   }
1450
1451   @Override
1452   public AlignmentI getAlignment()
1453   {
1454     return av.getAlignment();
1455   }
1456
1457   /**
1458    * get the name for this view
1459    * @return 
1460    */
1461   public String getViewName()
1462   {
1463     return av.viewName;
1464   }
1465
1466   /**
1467    * Make/Unmake this alignment panel the current input focus
1468    * @param b
1469    */
1470   public void setSelected(boolean b)
1471   {
1472     try {
1473       alignFrame.setSelected(b);
1474       } catch (Exception ex) {};
1475       
1476     if (b)
1477     {
1478       alignFrame.setDisplayedView(this);
1479     } 
1480   }
1481
1482   @Override
1483   public StructureSelectionManager getStructureSelectionManager()
1484   {
1485     return av.getStructureSelectionManager();
1486   }
1487
1488   @Override
1489   public void raiseOOMWarning(String string, OutOfMemoryError error)
1490   {
1491     new OOMWarning(string,  error, this);
1492   }
1493
1494   public FeatureRenderer cloneFeatureRenderer()
1495   {
1496     
1497     return new FeatureRenderer(this);
1498   }
1499
1500   public void updateFeatureRenderer(FeatureRenderer fr)
1501   {
1502     fr.transferSettings(seqPanel.seqCanvas.getFeatureRenderer());
1503   }
1504
1505   public void updateFeatureRendererFrom(FeatureRenderer fr)
1506   {
1507     if (seqPanel.seqCanvas.getFeatureRenderer()!=null) {
1508       seqPanel.seqCanvas.getFeatureRenderer().transferSettings(fr);
1509     }
1510   }
1511 }