3994c29ec44589d8797fae32cca00007427faea2
[jalview.git] / src / jalview / gui / AlignmentPanel.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ 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
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.gui;
22
23 import jalview.analysis.AnnotationSorter;
24 import jalview.api.AlignViewportI;
25 import jalview.api.AlignmentViewPanel;
26 import jalview.bin.Cache;
27 import jalview.datamodel.AlignmentI;
28 import jalview.datamodel.HiddenColumns;
29 import jalview.datamodel.SearchResultsI;
30 import jalview.datamodel.SequenceFeature;
31 import jalview.datamodel.SequenceGroup;
32 import jalview.datamodel.SequenceI;
33 import jalview.io.HTMLOutput;
34 import jalview.jbgui.GAlignmentPanel;
35 import jalview.math.AlignmentDimension;
36 import jalview.schemes.ResidueProperties;
37 import jalview.structure.StructureSelectionManager;
38 import jalview.util.Comparison;
39 import jalview.util.MessageManager;
40 import jalview.util.Platform;
41 import jalview.viewmodel.ViewportListenerI;
42 import jalview.viewmodel.ViewportRanges;
43
44 import java.awt.BorderLayout;
45 import java.awt.Color;
46 import java.awt.Container;
47 import java.awt.Dimension;
48 import java.awt.Font;
49 import java.awt.FontMetrics;
50 import java.awt.Graphics;
51 import java.awt.Insets;
52 import java.awt.event.AdjustmentEvent;
53 import java.awt.event.AdjustmentListener;
54 import java.awt.event.ComponentAdapter;
55 import java.awt.event.ComponentEvent;
56 import java.awt.print.PageFormat;
57 import java.awt.print.Printable;
58 import java.awt.print.PrinterException;
59 import java.beans.PropertyChangeEvent;
60 import java.beans.PropertyChangeListener;
61 import java.io.File;
62 import java.io.FileWriter;
63 import java.io.PrintWriter;
64 import java.util.List;
65
66 import javax.swing.SwingUtilities;
67
68 /**
69  * DOCUMENT ME!
70  * 
71  * @author $author$
72  * @version $Revision: 1.161 $
73  */
74 public class AlignmentPanel extends GAlignmentPanel implements
75         AdjustmentListener, Printable, AlignmentViewPanel,
76         ViewportListenerI
77 {
78   public AlignViewport av;
79
80   ViewportRanges vpRanges;
81
82   OverviewPanel overviewPanel;
83
84   private SeqPanel seqPanel;
85
86   private IdPanel idPanel;
87
88   private boolean headless;
89
90   IdwidthAdjuster idwidthAdjuster;
91
92   /** DOCUMENT ME!! */
93   public AlignFrame alignFrame;
94
95   private ScalePanel scalePanel;
96
97   private AnnotationPanel annotationPanel;
98
99   private AnnotationLabels alabels;
100
101   // this value is set false when selection area being dragged
102   boolean fastPaint = true;
103
104   private int hextent = 0;
105
106   private int vextent = 0;
107
108   /*
109    * Flag set while scrolling to follow complementary cDNA/protein scroll. When
110    * false, suppresses invoking the same method recursively.
111    */
112   private boolean scrollComplementaryPanel = true;
113
114   private PropertyChangeListener propertyChangeListener;
115
116   private CalculationChooser calculationDialog;
117
118   /**
119    * Creates a new AlignmentPanel object.
120    * 
121    * @param af
122    * @param av
123    */
124   public AlignmentPanel(AlignFrame af, final AlignViewport av)
125   {
126     alignFrame = af;
127     this.av = av;
128     vpRanges = av.getRanges();
129     setSeqPanel(new SeqPanel(av, this));
130     setIdPanel(new IdPanel(av, this));
131
132     setScalePanel(new ScalePanel(av, this));
133
134     idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
135     idwidthAdjuster = new IdwidthAdjuster(this);
136     idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
137
138     setAnnotationPanel(new AnnotationPanel(this));
139     setAlabels(new AnnotationLabels(this));
140
141     annotationScroller.setViewportView(getAnnotationPanel());
142     annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
143
144     scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
145     seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
146
147     setScrollValues(0, 0);
148
149     hscroll.addAdjustmentListener(this);
150     vscroll.addAdjustmentListener(this);
151
152     addComponentListener(new ComponentAdapter()
153     {
154       @Override
155       public void componentResized(ComponentEvent evt)
156       {
157         // reset the viewport ranges when the alignment panel is resized
158         // in particular, this initialises the end residue value when Jalview
159         // is initialised
160         if (av.getWrapAlignment())
161         {
162           int widthInRes = getSeqPanel().seqCanvas
163                   .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
164           vpRanges.setViewportWidth(widthInRes);
165         }
166         else
167         {
168           int widthInRes = getSeqPanel().seqCanvas.getWidth()
169                   / av.getCharWidth();
170           int heightInSeq = getSeqPanel().seqCanvas.getHeight()
171                   / av.getCharHeight();
172           
173           vpRanges.setViewportWidth(widthInRes);
174           vpRanges.setViewportHeight(heightInSeq);
175         }
176       }
177
178     });
179
180     final AlignmentPanel ap = this;
181     propertyChangeListener = new PropertyChangeListener()
182     {
183       @Override
184       public void propertyChange(PropertyChangeEvent evt)
185       {
186         if (evt.getPropertyName().equals("alignment"))
187         {
188           PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
189           alignmentChanged();
190         }
191       }
192     };
193     av.addPropertyChangeListener(propertyChangeListener);
194
195     av.getRanges().addPropertyChangeListener(this);
196     fontChanged();
197     adjustAnnotationHeight();
198     updateLayout();
199   }
200
201   @Override
202   public AlignViewportI getAlignViewport()
203   {
204     return av;
205   }
206
207   public void alignmentChanged()
208   {
209     av.alignmentChanged(this);
210
211     if (getCalculationDialog() != null)
212     {
213       getCalculationDialog().validateCalcTypes();
214     }
215
216     alignFrame.updateEditMenuBar();
217
218     paintAlignment(true);
219
220   }
221
222   /**
223    * DOCUMENT ME!
224    */
225   public void fontChanged()
226   {
227     // set idCanvas bufferedImage to null
228     // to prevent drawing old image
229     FontMetrics fm = getFontMetrics(av.getFont());
230
231     scalePanelHolder.setPreferredSize(new Dimension(10, av.getCharHeight()
232             + fm.getDescent()));
233     idSpaceFillerPanel1.setPreferredSize(new Dimension(10, av
234             .getCharHeight() + fm.getDescent()));
235
236     getIdPanel().getIdCanvas().gg = null;
237     getSeqPanel().seqCanvas.img = null;
238     getAnnotationPanel().adjustPanelHeight();
239
240     Dimension d = calculateIdWidth();
241
242     d.setSize(d.width + 4, d.height);
243     getIdPanel().getIdCanvas().setPreferredSize(d);
244     hscrollFillerPanel.setPreferredSize(d);
245
246     if (this.alignFrame.getSplitViewContainer() != null)
247     {
248       ((SplitFrame) this.alignFrame.getSplitViewContainer()).adjustLayout();
249     }
250
251     repaint();
252   }
253
254   /**
255    * Calculate the width of the alignment labels based on the displayed names
256    * and any bounds on label width set in preferences.
257    * 
258    * @return Dimension giving the maximum width of the alignment label panel
259    *         that should be used.
260    */
261   public Dimension calculateIdWidth()
262   {
263     // calculate sensible default width when no preference is available
264     Dimension r = null;
265     if (av.getIdWidth() < 0)
266     {
267       int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
268       int maxwidth = Math.max(20, Math.min(afwidth - 200, 2 * afwidth / 3));
269       r = calculateIdWidth(maxwidth);
270       av.setIdWidth(r.width);
271     }
272     else
273     {
274       r = new Dimension();
275       r.width = av.getIdWidth();
276       r.height = 0;
277     }
278     return r;
279   }
280
281   /**
282    * Calculate the width of the alignment labels based on the displayed names
283    * and any bounds on label width set in preferences.
284    * 
285    * @param maxwidth
286    *          -1 or maximum width allowed for IdWidth
287    * @return Dimension giving the maximum width of the alignment label panel
288    *         that should be used.
289    */
290   public Dimension calculateIdWidth(int maxwidth)
291   {
292     Container c = new Container();
293
294     FontMetrics fm = c.getFontMetrics(new Font(av.font.getName(),
295             Font.ITALIC, av.font.getSize()));
296
297     AlignmentI al = av.getAlignment();
298     int i = 0;
299     int idWidth = 0;
300     String id;
301
302     while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
303     {
304       SequenceI s = al.getSequenceAt(i);
305
306       id = s.getDisplayId(av.getShowJVSuffix());
307
308       if (fm.stringWidth(id) > idWidth)
309       {
310         idWidth = fm.stringWidth(id);
311       }
312
313       i++;
314     }
315
316     // Also check annotation label widths
317     i = 0;
318
319     if (al.getAlignmentAnnotation() != null)
320     {
321       fm = c.getFontMetrics(getAlabels().getFont());
322
323       while (i < al.getAlignmentAnnotation().length)
324       {
325         String label = al.getAlignmentAnnotation()[i].label;
326
327         if (fm.stringWidth(label) > idWidth)
328         {
329           idWidth = fm.stringWidth(label);
330         }
331
332         i++;
333       }
334     }
335
336     return new Dimension(maxwidth < 0 ? idWidth : Math.min(maxwidth,
337             idWidth), 12);
338   }
339
340   /**
341    * Highlight the given results on the alignment.
342    * 
343    */
344   public void highlightSearchResults(SearchResultsI results)
345   {
346     scrollToPosition(results);
347     getSeqPanel().seqCanvas.highlightSearchResults(results);
348   }
349
350   /**
351    * Scroll the view to show the position of the highlighted region in results
352    * (if any) and redraw the overview
353    * 
354    * @param results
355    */
356   public boolean scrollToPosition(SearchResultsI results)
357   {
358     return scrollToPosition(results, 0, true, false);
359   }
360
361   /**
362    * Scroll the view to show the position of the highlighted region in results
363    * (if any)
364    * 
365    * @param searchResults
366    * @param redrawOverview
367    * @return
368    */
369   public boolean scrollToPosition(SearchResultsI searchResults,
370           boolean redrawOverview)
371   {
372     return scrollToPosition(searchResults, 0, redrawOverview, false);
373   }
374
375   /**
376    * Scroll the view to show the position of the highlighted region in results
377    * (if any)
378    * 
379    * @param results
380    * @param verticalOffset
381    *          if greater than zero, allows scrolling to a position below the
382    *          first displayed sequence
383    * @param redrawOverview
384    *          - when set, the overview will be recalculated (takes longer)
385    * @param centre
386    *          if true, try to centre the search results horizontally in the view
387    * @return false if results were not found
388    */
389   public boolean scrollToPosition(SearchResultsI results,
390           int verticalOffset, boolean redrawOverview, boolean centre)
391   {
392     int startv, endv, starts, ends;
393     // TODO: properly locate search results in view when large numbers of hidden
394     // columns exist before highlighted region
395     // do we need to scroll the panel?
396     // TODO: tons of nullpointerexceptions raised here.
397     if (results != null && results.getSize() > 0 && av != null
398             && av.getAlignment() != null)
399     {
400       int seqIndex = av.getAlignment().findIndex(results);
401       if (seqIndex == -1)
402       {
403         return false;
404       }
405       SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
406
407       int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
408       if (r == null)
409       {
410         return false;
411       }
412       int start = r[0];
413       int end = r[1];
414
415       /*
416        * To centre results, scroll to positions half the visible width
417        * left/right of the start/end positions
418        */
419       if (centre)
420       {
421         int offset = (vpRanges.getEndRes() - vpRanges.getStartRes() + 1) / 2
422                 - 1;
423         start = Math.max(start - offset, 0);
424         end = end + offset - 1;
425       }
426       if (start < 0)
427       {
428         return false;
429       }
430       if (end == seq.getEnd())
431       {
432         return false;
433       }
434       if (av.hasHiddenColumns())
435       {
436         HiddenColumns hidden = av.getAlignment().getHiddenColumns();
437         start = hidden.findColumnPosition(start);
438         end = hidden.findColumnPosition(end);
439         if (start == end)
440         {
441           if (!hidden.isVisible(r[0]))
442           {
443             // don't scroll - position isn't visible
444             return false;
445           }
446         }
447       }
448
449       /*
450        * allow for offset of target sequence (actually scroll to one above it)
451        */
452       seqIndex = Math.max(0, seqIndex - verticalOffset);
453
454       if (!av.getWrapAlignment())
455       {
456         if ((startv = vpRanges.getStartRes()) >= start)
457         {
458           /*
459            * Scroll left to make start of search results visible
460            */
461           setScrollValues(start, seqIndex);
462         }
463         else if ((endv = vpRanges.getEndRes()) <= end)
464         {
465           /*
466            * Scroll right to make end of search results visible
467            */
468           setScrollValues(startv + end - endv, seqIndex);
469         }
470         else if ((starts = vpRanges.getStartSeq()) > seqIndex)
471         {
472           /*
473            * Scroll up to make start of search results visible
474            */
475           setScrollValues(vpRanges.getStartRes(), seqIndex);
476         }
477         else if ((ends = vpRanges.getEndSeq()) <= seqIndex)
478         {
479           /*
480            * Scroll down to make end of search results visible
481            */
482           setScrollValues(vpRanges.getStartRes(), starts + seqIndex - ends
483                   + 1);
484         }
485         /*
486          * Else results are already visible - no need to scroll
487          */
488       }
489       else
490       {
491         vpRanges.scrollToWrappedVisible(start);
492       }
493     }
494
495     paintAlignment(redrawOverview);
496     return true;
497   }
498
499   /**
500    * DOCUMENT ME!
501    * 
502    * @return DOCUMENT ME!
503    */
504   public OverviewPanel getOverviewPanel()
505   {
506     return overviewPanel;
507   }
508
509   /**
510    * DOCUMENT ME!
511    * 
512    * @param op
513    *          DOCUMENT ME!
514    */
515   public void setOverviewPanel(OverviewPanel op)
516   {
517     overviewPanel = op;
518   }
519
520   /**
521    * 
522    * @param b
523    *          Hide or show annotation panel
524    * 
525    */
526   public void setAnnotationVisible(boolean b)
527   {
528     if (!av.getWrapAlignment())
529     {
530       annotationSpaceFillerHolder.setVisible(b);
531       annotationScroller.setVisible(b);
532     }
533     repaint();
534   }
535
536   /**
537    * automatically adjust annotation panel height for new annotation whilst
538    * ensuring the alignment is still visible.
539    */
540   @Override
541   public void adjustAnnotationHeight()
542   {
543     // TODO: display vertical annotation scrollbar if necessary
544     // this is called after loading new annotation onto alignment
545     if (alignFrame.getHeight() == 0)
546     {
547       System.out.println("NEEDS FIXING");
548     }
549     validateAnnotationDimensions(true);
550     addNotify();
551     paintAlignment(true);
552   }
553
554   /**
555    * calculate the annotation dimensions and refresh slider values accordingly.
556    * need to do repaints/notifys afterwards.
557    */
558   protected void validateAnnotationDimensions(boolean adjustPanelHeight)
559   {
560     int annotationHeight = getAnnotationPanel().adjustPanelHeight();
561
562     if (adjustPanelHeight)
563     {
564       int rowHeight = av.getCharHeight();
565       int alignmentHeight = rowHeight * av.getAlignment().getHeight();
566
567       /*
568        * Estimate available height in the AlignFrame for alignment +
569        * annotations. Deduct an estimate for title bar, menu bar, scale panel,
570        * hscroll, status bar (as these are not laid out we can't inspect their
571        * actual heights). Insets gives frame borders.
572        */
573       int stuff = Platform.isAMac() ? 80 : 100;
574       Insets insets = alignFrame.getInsets();
575       int availableHeight = alignFrame.getHeight() - stuff - insets.top
576               - insets.bottom;
577
578       /*
579        * If not enough vertical space, maximize annotation height while keeping
580        * at least two rows of alignment visible
581        */
582       if (annotationHeight + alignmentHeight > availableHeight)
583       {
584         annotationHeight = Math.min(annotationHeight, availableHeight - 2
585                 * rowHeight);
586       }
587     }
588     else
589     {
590       // maintain same window layout whilst updating sliders
591       annotationHeight = annotationScroller.getSize().height;
592     }
593     hscroll.addNotify();
594
595     annotationScroller.setPreferredSize(new Dimension(annotationScroller
596             .getWidth(), annotationHeight));
597
598     Dimension e = idPanel.getSize();
599     alabels.setSize(new Dimension(e.width, annotationHeight));
600
601     annotationSpaceFillerHolder.setPreferredSize(new Dimension(
602             annotationSpaceFillerHolder.getWidth(), annotationHeight));
603     annotationScroller.validate();
604     annotationScroller.addNotify();
605   }
606
607   /**
608    * update alignment layout for viewport settings
609    * 
610    * @param wrap
611    *          DOCUMENT ME!
612    */
613   public void updateLayout()
614   {
615     fontChanged();
616     setAnnotationVisible(av.isShowAnnotation());
617     boolean wrap = av.getWrapAlignment();
618     vpRanges.setStartSeq(0);
619     scalePanelHolder.setVisible(!wrap);
620     hscroll.setVisible(!wrap);
621     idwidthAdjuster.setVisible(!wrap);
622
623     if (wrap)
624     {
625       annotationScroller.setVisible(false);
626       annotationSpaceFillerHolder.setVisible(false);
627     }
628     else if (av.isShowAnnotation())
629     {
630       annotationScroller.setVisible(true);
631       annotationSpaceFillerHolder.setVisible(true);
632     }
633
634     if (wrap)
635     {
636       int widthInRes = getSeqPanel().seqCanvas
637               .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
638       vpRanges.setViewportWidth(widthInRes);
639     }
640     else
641     {
642       int widthInRes = (getSeqPanel().seqCanvas.getWidth() / av
643               .getCharWidth()) - 1;
644       int heightInSeq = (getSeqPanel().seqCanvas.getHeight() / av
645               .getCharHeight()) - 1;
646
647       vpRanges.setViewportWidth(widthInRes);
648       vpRanges.setViewportHeight(heightInSeq);
649     }
650
651     idSpaceFillerPanel1.setVisible(!wrap);
652
653     repaint();
654   }
655
656
657   /**
658    * Adjust row/column scrollers to show a visible position in the alignment.
659    * 
660    * @param x
661    *          visible column to scroll to
662    * @param y
663    *          visible row to scroll to
664    * 
665    */
666   public void setScrollValues(int xpos, int ypos)
667   {
668     int x = xpos;
669     int y = ypos;
670
671     if (av == null || av.getAlignment() == null)
672     {
673       return;
674     }
675
676     if (av.getWrapAlignment())
677     {
678       setScrollingForWrappedPanel(x);
679     }
680     else
681     {
682       int width = av.getAlignment().getWidth();
683       int height = av.getAlignment().getHeight();
684
685       if (av.hasHiddenColumns())
686       {
687         // reset the width to exclude hidden columns
688         width = av.getAlignment().getHiddenColumns().findColumnPosition(width);
689       }
690
691       hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
692       vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
693
694       if (hextent > width)
695       {
696         hextent = width;
697       }
698
699       if (vextent > height)
700       {
701         vextent = height;
702       }
703
704       if ((hextent + x) > width)
705       {
706         x = width - hextent;
707       }
708
709       if ((vextent + y) > height)
710       {
711         y = height - vextent;
712       }
713
714       if (y < 0)
715       {
716         y = 0;
717       }
718
719       if (x < 0)
720       {
721         x = 0;
722       }
723
724       // update the scroll values
725       hscroll.setValues(x, hextent, 0, width);
726       vscroll.setValues(y, vextent, 0, height);
727     }
728   }
729
730   /**
731    * Respond to adjustment event when horizontal or vertical scrollbar is
732    * changed
733    * 
734    * @param evt
735    *          adjustment event encoding whether hscroll or vscroll changed
736    */
737   @Override
738   public void adjustmentValueChanged(AdjustmentEvent evt)
739   {
740     int oldX = vpRanges.getStartRes();
741     int oldwidth = vpRanges.getViewportWidth();
742     int oldY = vpRanges.getStartSeq();
743     int oldheight = vpRanges.getViewportHeight();
744
745     if (av.getWrapAlignment())
746     {
747       if (evt.getSource() == hscroll)
748       {
749         return; // no horizontal scroll when wrapped
750       }
751       else if (evt.getSource() == vscroll)
752       {
753         int offy = vscroll.getValue();
754         int rowSize = getSeqPanel().seqCanvas
755                 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
756
757         // if we're scrolling to the position we're already at, stop
758         // this prevents infinite recursion of events when the scroll/viewport
759         // ranges values are the same
760         int newX = offy * rowSize;
761         if ((newX == oldX) && (oldwidth == rowSize))
762         {
763           return;
764         }
765         else if (offy > -1)
766         {
767           /*
768            * throttle to one width's worth at a time (so click in
769            * scrollbar doesn't jump over data)
770            */
771           newX = newX > oldX ? oldX + rowSize : oldX - rowSize;
772           vpRanges.setViewportStartAndWidth(newX, rowSize);
773         }
774       }
775       else
776       {
777         // This is only called if file loaded is a jar file that
778         // was wrapped when saved and user has wrap alignment true
779         // as preference setting
780         SwingUtilities.invokeLater(new Runnable()
781         {
782           @Override
783           public void run()
784         {
785             // When updating scrolling to use ViewportChange events, this code
786             // could not be validated and it is not clear if it is now being
787             // called. Log warning here in case it is called and unforeseen
788             // problems occur
789             Cache.log
790                     .warn("Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
791
792             // scroll to start of panel
793             vpRanges.setStartRes(0);
794             vpRanges.setStartSeq(0);
795           }
796         });
797       }
798       repaint();
799     }
800     else
801     {
802       // horizontal scroll
803       if (evt.getSource() == hscroll)
804       {
805         int x = hscroll.getValue();
806         int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
807
808         // if we're scrolling to the position we're already at, stop
809         // this prevents infinite recursion of events when the scroll/viewport
810         // ranges values are the same
811         if ((x == oldX) && (width == oldwidth))
812         {
813           return;
814         }
815         vpRanges.setViewportStartAndWidth(x, width);
816       }
817       else if (evt.getSource() == vscroll)
818       {
819         int y = vscroll.getValue();
820         int height = getSeqPanel().seqCanvas.getHeight()
821                 / av.getCharHeight();
822
823         // if we're scrolling to the position we're already at, stop
824         // this prevents infinite recursion of events when the scroll/viewport
825         // ranges values are the same
826         if ((y == oldY) && (height == oldheight))
827         {
828           return;
829         }
830         vpRanges.setViewportStartAndHeight(y, height);
831       }
832       if (!fastPaint)
833       {
834         repaint();
835       }
836     }
837   }
838
839   /**
840    * Repaint the alignment including the annotations and overview panels (if
841    * shown).
842    */
843   @Override
844   public void paintAlignment(boolean updateOverview)
845   {
846     final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
847             av.isShowAutocalculatedAbove());
848     sorter.sort(getAlignment().getAlignmentAnnotation(),
849             av.getSortAnnotationsBy());
850     repaint();
851
852     if (updateOverview)
853     {
854       // TODO: determine if this paintAlignment changed structure colours
855       av.getStructureSelectionManager().sequenceColoursChanged(this);
856
857       if (overviewPanel != null)
858       {
859         overviewPanel.updateOverviewImage();
860       }
861     }
862   }
863
864   /**
865    * DOCUMENT ME!
866    * 
867    * @param g
868    *          DOCUMENT ME!
869    */
870   @Override
871   public void paintComponent(Graphics g)
872   {
873     invalidate();
874
875     Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
876     idPanelHolder.setPreferredSize(d);
877     hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
878     validate();
879
880     /*
881      * set scroll bar positions
882      */
883     setScrollValues(vpRanges.getStartRes(), vpRanges.getStartSeq());
884   }
885
886   /*
887    * Set vertical scroll bar parameters for wrapped panel
888    * @param res 
889    *    the residue to scroll to
890    */
891   private void setScrollingForWrappedPanel(int res)
892   {
893     // get the width of the alignment in residues
894     int maxwidth = av.getAlignment().getWidth();
895     if (av.hasHiddenColumns())
896     {
897         maxwidth = av.getAlignment().getHiddenColumns()
898                 .findColumnPosition(maxwidth) - 1;
899     }
900
901     // get the width of the canvas in residues
902     int canvasWidth = getSeqPanel().seqCanvas
903             .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
904     if (canvasWidth > 0)
905     {
906       // position we want to scroll to is number of canvasWidth's to get there
907       int current = res / canvasWidth;
908
909       // max scroll position: add one because extent is 1 and scrollbar value
910       // can only be set to at most max - extent
911       int max = maxwidth / canvasWidth + 1;
912       vscroll.setUnitIncrement(1);
913       vscroll.setValues(current, 1, 0, max);
914     }
915   }
916
917   /**
918    * DOCUMENT ME!
919    * 
920    * @param pg
921    *          DOCUMENT ME!
922    * @param pf
923    *          DOCUMENT ME!
924    * @param pi
925    *          DOCUMENT ME!
926    * 
927    * @return DOCUMENT ME!
928    * 
929    * @throws PrinterException
930    *           DOCUMENT ME!
931    */
932   @Override
933   public int print(Graphics pg, PageFormat pf, int pi)
934           throws PrinterException
935   {
936     pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
937
938     int pwidth = (int) pf.getImageableWidth();
939     int pheight = (int) pf.getImageableHeight();
940
941     if (av.getWrapAlignment())
942     {
943       return printWrappedAlignment(pwidth, pheight, pi, pg);
944     }
945     else
946     {
947       return printUnwrapped(pwidth, pheight, pi, pg, pg);
948     }
949   }
950
951   /**
952    * DOCUMENT ME!
953    * 
954    * @param pg
955    *          DOCUMENT ME!
956    * @param pwidth
957    *          DOCUMENT ME!
958    * @param pheight
959    *          DOCUMENT ME!
960    * @param pi
961    *          DOCUMENT ME!
962    * 
963    * @return DOCUMENT ME!
964    * 
965    * @throws PrinterException
966    *           DOCUMENT ME!
967    */
968   /**
969    * Draws the alignment image, including sequence ids, sequences, and
970    * annotation labels and annotations if shown, on either one or two Graphics
971    * context.
972    * 
973    * @param pageWidth
974    * @param pageHeight
975    * @param pi
976    * @param idGraphics
977    *          the graphics context for sequence ids and annotation labels
978    * @param alignmentGraphics
979    *          the graphics context for sequences and annotations (may or may not
980    *          be the same context as idGraphics)
981    * @return
982    * @throws PrinterException
983    */
984   public int printUnwrapped(int pageWidth, int pageHeight, int pi,
985           Graphics idGraphics, Graphics alignmentGraphics)
986           throws PrinterException
987   {
988     final int idWidth = getVisibleIdWidth(false);
989
990     /*
991      * Get the horizontal offset to where we draw the sequences.
992      * This is idWidth if using a single Graphics context, else zero.
993      */
994     final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0 : idWidth;
995
996     FontMetrics fm = getFontMetrics(av.getFont());
997     int charHeight = av.getCharHeight();
998     int scaleHeight = charHeight + fm.getDescent();
999
1000     idGraphics.setColor(Color.white);
1001     idGraphics.fillRect(0, 0, pageWidth, pageHeight);
1002     idGraphics.setFont(av.getFont());
1003
1004     /*
1005      * How many sequences and residues can we fit on a printable page?
1006      */
1007     int totalRes = (pageWidth - idWidth) / av.getCharWidth();
1008
1009     int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
1010
1011     int alignmentWidth = av.getAlignment().getWidth();
1012     int pagesWide = (alignmentWidth / totalRes) + 1;
1013
1014     final int startRes = (pi % pagesWide) * totalRes;
1015     int endRes = (startRes + totalRes) - 1;
1016
1017     if (endRes > (alignmentWidth - 1))
1018     {
1019       endRes = alignmentWidth - 1;
1020     }
1021
1022     final int startSeq = (pi / pagesWide) * totalSeq;
1023     int endSeq = startSeq + totalSeq;
1024
1025     int alignmentHeight = av.getAlignment().getHeight();
1026     if (endSeq > alignmentHeight)
1027     {
1028       endSeq = alignmentHeight;
1029     }
1030
1031     int pagesHigh = ((alignmentHeight / totalSeq) + 1)
1032             * pageHeight;
1033
1034     if (av.isShowAnnotation())
1035     {
1036       pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
1037     }
1038
1039     pagesHigh /= pageHeight;
1040
1041     if (pi >= (pagesWide * pagesHigh))
1042     {
1043       return Printable.NO_SUCH_PAGE;
1044     }
1045     final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight
1046             + 3;
1047
1048     /*
1049      * draw the Scale at horizontal offset, then reset to top left (0, 0)
1050      */
1051     alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1052     getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1053             pageWidth - idWidth, scaleHeight);
1054     alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1055
1056     /*
1057      * Draw the sequence ids, offset for scale height,
1058      * then reset to top left (0, 0)
1059      */
1060     idGraphics.translate(0, scaleHeight);
1061     idGraphics.setFont(getIdPanel().getIdCanvas().getIdfont());
1062     Color currentColor = null;
1063     Color currentTextColor = null;
1064
1065     SequenceI seq;
1066     for (int i = startSeq; i < endSeq; i++)
1067     {
1068       seq = av.getAlignment().getSequenceAt(i);
1069       if ((av.getSelectionGroup() != null)
1070               && av.getSelectionGroup().getSequences(null).contains(seq))
1071       {
1072         /*
1073          * gray out ids of sequences in selection group (if any)
1074          */
1075         currentColor = Color.gray;
1076         currentTextColor = Color.black;
1077       }
1078       else
1079       {
1080         currentColor = av.getSequenceColour(seq);
1081         currentTextColor = Color.black;
1082       }
1083
1084       idGraphics.setColor(currentColor);
1085       idGraphics.fillRect(0, (i - startSeq) * charHeight, idWidth,
1086               charHeight);
1087
1088       idGraphics.setColor(currentTextColor);
1089
1090       int xPos = 0;
1091       String displayId = seq.getDisplayId(av.getShowJVSuffix());
1092       if (av.isRightAlignIds())
1093       {
1094         fm = idGraphics.getFontMetrics();
1095         xPos = idWidth
1096                 - fm.stringWidth(displayId)
1097                 - 4;
1098       }
1099
1100       idGraphics.drawString(displayId, xPos,
1101               (((i - startSeq) * charHeight) + charHeight)
1102                       - (charHeight / 5));
1103     }
1104     idGraphics.setFont(av.getFont());
1105     idGraphics.translate(0, -scaleHeight);
1106
1107     /*
1108      * draw the sequences, offset for scale height, and id width (if using a
1109      * single graphics context), then reset to (0, scale height)
1110      */
1111     alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1112     getSeqPanel().seqCanvas.drawPanel(alignmentGraphics, startRes, endRes,
1113             startSeq, endSeq, 0);
1114     alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1115
1116     if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1117     {
1118       /*
1119        * draw annotation labels; drawComponent() translates by
1120        * getScrollOffset(), so compensate for that first;
1121        * then reset to (0, scale height)
1122        */
1123       int offset = getAlabels().getScrollOffset();
1124       idGraphics.translate(0, -offset);
1125       idGraphics.translate(0, alignmentDrawnHeight);
1126       getAlabels().drawComponent(idGraphics, idWidth);
1127       idGraphics.translate(0, -alignmentDrawnHeight);
1128
1129       /*
1130        * draw the annotations starting at 
1131        * (idOffset, alignmentHeight) from (0, scaleHeight)
1132        */
1133       alignmentGraphics.translate(alignmentGraphicsOffset, alignmentDrawnHeight);
1134       getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1135               alignmentGraphics, -1, startRes, endRes + 1);
1136     }
1137
1138     return Printable.PAGE_EXISTS;
1139   }
1140
1141   /**
1142    * DOCUMENT ME!
1143    * 
1144    * @param pg
1145    *          DOCUMENT ME!
1146    * @param pwidth
1147    *          DOCUMENT ME!
1148    * @param pheight
1149    *          DOCUMENT ME!
1150    * @param pi
1151    *          DOCUMENT ME!
1152    * 
1153    * @return DOCUMENT ME!
1154    * 
1155    * @throws PrinterException
1156    *           DOCUMENT ME!
1157    */
1158   public int printWrappedAlignment(int pwidth, int pheight, int pi,
1159           Graphics pg) throws PrinterException
1160   {
1161     int annotationHeight = 0;
1162     AnnotationLabels labels = null;
1163     if (av.isShowAnnotation())
1164     {
1165       annotationHeight = getAnnotationPanel().adjustPanelHeight();
1166       labels = new AnnotationLabels(av);
1167     }
1168
1169     int hgap = av.getCharHeight();
1170     if (av.getScaleAboveWrapped())
1171     {
1172       hgap += av.getCharHeight();
1173     }
1174
1175     int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1176             + annotationHeight;
1177
1178     int idWidth = getVisibleIdWidth(false);
1179
1180     int maxwidth = av.getAlignment().getWidth();
1181     if (av.hasHiddenColumns())
1182     {
1183       maxwidth = av.getAlignment().getHiddenColumns()
1184               .findColumnPosition(maxwidth) - 1;
1185     }
1186
1187     int resWidth = getSeqPanel().seqCanvas.getWrappedCanvasWidth(pwidth
1188             - idWidth);
1189
1190     int totalHeight = cHeight * (maxwidth / resWidth + 1);
1191
1192     pg.setColor(Color.white);
1193     pg.fillRect(0, 0, pwidth, pheight);
1194     pg.setFont(av.getFont());
1195
1196     // //////////////
1197     // Draw the ids
1198     pg.setColor(Color.black);
1199
1200     pg.translate(0, -pi * pheight);
1201
1202     pg.setClip(0, pi * pheight, pwidth, pheight);
1203
1204     int ypos = hgap;
1205
1206     do
1207     {
1208       for (int i = 0; i < av.getAlignment().getHeight(); i++)
1209       {
1210         pg.setFont(getIdPanel().getIdCanvas().getIdfont());
1211         SequenceI s = av.getAlignment().getSequenceAt(i);
1212         String string = s.getDisplayId(av.getShowJVSuffix());
1213         int xPos = 0;
1214         if (av.isRightAlignIds())
1215         {
1216           FontMetrics fm = pg.getFontMetrics();
1217           xPos = idWidth - fm.stringWidth(string) - 4;
1218         }
1219         pg.drawString(string, xPos,
1220                 ((i * av.getCharHeight()) + ypos + av.getCharHeight())
1221                         - (av.getCharHeight() / 5));
1222       }
1223       if (labels != null)
1224       {
1225         pg.translate(-3,
1226                 ypos + (av.getAlignment().getHeight() * av.getCharHeight()));
1227
1228         pg.setFont(av.getFont());
1229         labels.drawComponent(pg, idWidth);
1230         pg.translate(
1231                 +3,
1232                 -ypos
1233                         - (av.getAlignment().getHeight() * av
1234                                 .getCharHeight()));
1235       }
1236
1237       ypos += cHeight;
1238     } while (ypos < totalHeight);
1239
1240     pg.translate(idWidth, 0);
1241
1242     getSeqPanel().seqCanvas.drawWrappedPanel(pg, pwidth - idWidth,
1243             totalHeight, 0);
1244
1245     if ((pi * pheight) < totalHeight)
1246     {
1247       return Printable.PAGE_EXISTS;
1248
1249     }
1250     else
1251     {
1252       return Printable.NO_SUCH_PAGE;
1253     }
1254   }
1255
1256   /**
1257    * get current sequence ID panel width, or nominal value if panel were to be
1258    * displayed using default settings
1259    * 
1260    * @return
1261    */
1262   public int getVisibleIdWidth()
1263   {
1264     return getVisibleIdWidth(true);
1265   }
1266
1267   /**
1268    * get current sequence ID panel width, or nominal value if panel were to be
1269    * displayed using default settings
1270    * 
1271    * @param onscreen
1272    *          indicate if the Id width for onscreen or offscreen display should
1273    *          be returned
1274    * @return
1275    */
1276   public int getVisibleIdWidth(boolean onscreen)
1277   {
1278     // see if rendering offscreen - check preferences and calc width accordingly
1279     if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1280     {
1281       return calculateIdWidth(-1).width + 4;
1282     }
1283     Integer idwidth = null;
1284     if (onscreen
1285             || (idwidth = Cache.getIntegerProperty("FIGURE_FIXEDIDWIDTH")) == null)
1286     {
1287       int w = getIdPanel().getWidth();
1288       return (w > 0 ? w : calculateIdWidth().width + 4);
1289     }
1290     return idwidth.intValue() + 4;
1291   }
1292
1293   void makeAlignmentImage(jalview.util.ImageMaker.TYPE type, File file)
1294   {
1295     int boarderBottomOffset = 5;
1296     long pSessionId = System.currentTimeMillis();
1297     headless = (System.getProperty("java.awt.headless") != null && System
1298             .getProperty("java.awt.headless").equals("true"));
1299     if (alignFrame != null && !headless)
1300     {
1301       if (file != null)
1302       {
1303         alignFrame.setProgressBar(MessageManager.formatMessage(
1304                 "status.saving_file", new Object[] { type.getLabel() }),
1305                 pSessionId);
1306       }
1307     }
1308     try
1309     {
1310       AlignmentDimension aDimension = getAlignmentDimension();
1311       try
1312       {
1313         jalview.util.ImageMaker im;
1314         final String imageAction, imageTitle;
1315         if (type == jalview.util.ImageMaker.TYPE.PNG)
1316         {
1317           imageAction = "Create PNG image from alignment";
1318           imageTitle = null;
1319         }
1320         else if (type == jalview.util.ImageMaker.TYPE.EPS)
1321         {
1322           imageAction = "Create EPS file from alignment";
1323           imageTitle = alignFrame.getTitle();
1324         }
1325         else
1326         {
1327           imageAction = "Create SVG file from alignment";
1328           imageTitle = alignFrame.getTitle();
1329         }
1330
1331         im = new jalview.util.ImageMaker(this, type, imageAction,
1332                 aDimension.getWidth(), aDimension.getHeight()
1333                         + boarderBottomOffset, file, imageTitle,
1334                 alignFrame, pSessionId, headless);
1335         Graphics graphics = im.getGraphics();
1336         if (av.getWrapAlignment())
1337         {
1338           if (graphics != null)
1339           {
1340             printWrappedAlignment(aDimension.getWidth(),
1341                     aDimension.getHeight() + boarderBottomOffset, 0,
1342                     graphics);
1343             im.writeImage();
1344           }
1345         }
1346         else
1347         {
1348           if (graphics != null)
1349           {
1350             printUnwrapped(aDimension.getWidth(), aDimension.getHeight(),
1351                     0, graphics, graphics);
1352             im.writeImage();
1353           }
1354         }
1355
1356       } catch (OutOfMemoryError err)
1357       {
1358         // Be noisy here.
1359         System.out.println("########################\n" + "OUT OF MEMORY "
1360                 + file + "\n" + "########################");
1361         new OOMWarning("Creating Image for " + file, err);
1362         // System.out.println("Create IMAGE: " + err);
1363       } catch (Exception ex)
1364       {
1365         ex.printStackTrace();
1366       }
1367     } finally
1368     {
1369
1370     }
1371   }
1372
1373   public AlignmentDimension getAlignmentDimension()
1374   {
1375     int maxwidth = av.getAlignment().getWidth();
1376     if (av.hasHiddenColumns())
1377     {
1378       maxwidth = av.getAlignment().getHiddenColumns()
1379               .findColumnPosition(maxwidth);
1380     }
1381
1382     int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1383             + getScalePanel().getHeight();
1384     int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1385
1386     if (av.getWrapAlignment())
1387     {
1388       height = getWrappedHeight();
1389       if (headless)
1390       {
1391         // need to obtain default alignment width and then add in any
1392         // additional allowance for id margin
1393         // this duplicates the calculation in getWrappedHeight but adjusts for
1394         // offscreen idWith
1395         width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1396                 - alignFrame.getInsets().left
1397                 - alignFrame.getInsets().right - getVisibleIdWidth()
1398                 + getVisibleIdWidth(false);
1399       }
1400       else
1401       {
1402         width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1403       }
1404
1405     }
1406     else if (av.isShowAnnotation())
1407     {
1408       height += getAnnotationPanel().adjustPanelHeight() + 3;
1409     }
1410     return new AlignmentDimension(width, height);
1411
1412   }
1413
1414   /**
1415    * DOCUMENT ME!
1416    */
1417   public void makeEPS(File epsFile)
1418   {
1419     makeAlignmentImage(jalview.util.ImageMaker.TYPE.EPS, epsFile);
1420   }
1421
1422   /**
1423    * DOCUMENT ME!
1424    */
1425   public void makePNG(File pngFile)
1426   {
1427     makeAlignmentImage(jalview.util.ImageMaker.TYPE.PNG, pngFile);
1428   }
1429
1430   public void makeSVG(File svgFile)
1431   {
1432     makeAlignmentImage(jalview.util.ImageMaker.TYPE.SVG, svgFile);
1433   }
1434
1435   public void makePNGImageMap(File imgMapFile, String imageName)
1436   {
1437     // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1438     // ////////////////////////////////////////////
1439     int idWidth = getVisibleIdWidth(false);
1440     FontMetrics fm = getFontMetrics(av.getFont());
1441     int scaleHeight = av.getCharHeight() + fm.getDescent();
1442
1443     // Gen image map
1444     // ////////////////////////////////
1445     if (imgMapFile != null)
1446     {
1447       try
1448       {
1449         int sSize = av.getAlignment().getHeight();
1450         int alwidth = av.getAlignment().getWidth();
1451         PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1452         out.println(HTMLOutput.getImageMapHTML());
1453         out.println("<img src=\"" + imageName
1454                 + "\" border=\"0\" usemap=\"#Map\" >"
1455                 + "<map name=\"Map\">");
1456
1457         for (int s = 0; s < sSize; s++)
1458         {
1459           int sy = s * av.getCharHeight() + scaleHeight;
1460
1461           SequenceI seq = av.getAlignment().getSequenceAt(s);
1462           SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1463           for (int column = 0; column < alwidth; column++)
1464           {
1465             StringBuilder text = new StringBuilder(512);
1466             String triplet = null;
1467             if (av.getAlignment().isNucleotide())
1468             {
1469               triplet = ResidueProperties.nucleotideName.get(seq
1470                       .getCharAt(column) + "");
1471             }
1472             else
1473             {
1474               triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(column)
1475                       + "");
1476             }
1477
1478             if (triplet == null)
1479             {
1480               continue;
1481             }
1482
1483             int seqPos = seq.findPosition(column);
1484             int gSize = groups.length;
1485             for (int g = 0; g < gSize; g++)
1486             {
1487               if (text.length() < 1)
1488               {
1489                 text.append("<area shape=\"rect\" coords=\"")
1490                         .append((idWidth + column * av.getCharWidth()))
1491                         .append(",").append(sy).append(",")
1492                         .append((idWidth + (column + 1) * av.getCharWidth()))
1493                         .append(",").append((av.getCharHeight() + sy))
1494                         .append("\"").append(" onMouseOver=\"toolTip('")
1495                         .append(seqPos).append(" ").append(triplet);
1496               }
1497
1498               if (groups[g].getStartRes() < column
1499                       && groups[g].getEndRes() > column)
1500               {
1501                 text.append("<br><em>").append(groups[g].getName())
1502                         .append("</em>");
1503               }
1504             }
1505
1506             if (text.length() < 1)
1507             {
1508               text.append("<area shape=\"rect\" coords=\"")
1509                       .append((idWidth + column * av.getCharWidth()))
1510                       .append(",").append(sy).append(",")
1511                       .append((idWidth + (column + 1) * av.getCharWidth()))
1512                       .append(",").append((av.getCharHeight() + sy))
1513                       .append("\"").append(" onMouseOver=\"toolTip('")
1514                       .append(seqPos).append(" ").append(triplet);
1515             }
1516             if (!Comparison.isGap(seq.getCharAt(column)))
1517             {
1518               List<SequenceFeature> features = seq.findFeatures(column, column);
1519               for (SequenceFeature sf : features)
1520               {
1521                 if (sf.isContactFeature())
1522                 {
1523                   text.append("<br>").append(sf.getType()).append(" ")
1524                           .append(sf.getBegin()).append(":")
1525                           .append(sf.getEnd());
1526                 }
1527                 else
1528                 {
1529                   text.append("<br>");
1530                   text.append(sf.getType());
1531                   String description = sf.getDescription();
1532                   if (description != null
1533                           && !sf.getType().equals(description))
1534                   {
1535                     description = description.replace("\"", "&quot;");
1536                     text.append(" ").append(description);
1537                   }
1538                 }
1539                 String status = sf.getStatus();
1540                 if (status != null && !"".equals(status))
1541                 {
1542                   text.append(" (").append(status).append(")");
1543                 }
1544               }
1545               if (text.length() > 1)
1546               {
1547                 text.append("')\"; onMouseOut=\"toolTip()\";  href=\"#\">");
1548                 out.println(text.toString());
1549               }
1550             }
1551           }
1552         }
1553         out.println("</map></body></html>");
1554         out.close();
1555
1556       } catch (Exception ex)
1557       {
1558         ex.printStackTrace();
1559       }
1560     } // /////////END OF IMAGE MAP
1561
1562   }
1563
1564   int getWrappedHeight()
1565   {
1566     int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1567
1568     if (System.getProperty("java.awt.headless") != null
1569             && System.getProperty("java.awt.headless").equals("true"))
1570     {
1571       seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1572               - vscroll.getPreferredSize().width
1573               - alignFrame.getInsets().left - alignFrame.getInsets().right;
1574     }
1575
1576     int chunkWidth = getSeqPanel().seqCanvas
1577             .getWrappedCanvasWidth(seqPanelWidth);
1578
1579     int hgap = av.getCharHeight();
1580     if (av.getScaleAboveWrapped())
1581     {
1582       hgap += av.getCharHeight();
1583     }
1584
1585     int annotationHeight = 0;
1586     if (av.isShowAnnotation())
1587     {
1588       annotationHeight = getAnnotationPanel().adjustPanelHeight();
1589     }
1590
1591     int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1592             + annotationHeight;
1593
1594     int maxwidth = av.getAlignment().getWidth();
1595     if (av.hasHiddenColumns())
1596     {
1597       maxwidth = av.getAlignment().getHiddenColumns()
1598               .findColumnPosition(maxwidth) - 1;
1599     }
1600
1601     int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1602
1603     return height;
1604   }
1605
1606   /**
1607    * close the panel - deregisters all listeners and nulls any references to
1608    * alignment data.
1609    */
1610   public void closePanel()
1611   {
1612     PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1613     PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1614     PaintRefresher.RemoveComponent(this);
1615
1616     closeChildFrames();
1617
1618     /*
1619      * try to ensure references are nulled
1620      */
1621     if (annotationPanel != null)
1622     {
1623       annotationPanel.dispose();
1624     }
1625
1626     if (av != null)
1627     {
1628       av.removePropertyChangeListener(propertyChangeListener);
1629       jalview.structure.StructureSelectionManager ssm = av
1630               .getStructureSelectionManager();
1631       ssm.removeStructureViewerListener(getSeqPanel(), null);
1632       ssm.removeSelectionListener(getSeqPanel());
1633       ssm.removeCommandListener(av);
1634       ssm.removeStructureViewerListener(getSeqPanel(), null);
1635       ssm.removeSelectionListener(getSeqPanel());
1636       av.dispose();
1637       av = null;
1638     }
1639     else
1640     {
1641       if (Cache.log.isDebugEnabled())
1642       {
1643         Cache.log.warn("Closing alignment panel which is already closed.");
1644       }
1645     }
1646   }
1647
1648   /**
1649    * Close any open dialogs that would be orphaned when this one is closed
1650    */
1651   protected void closeChildFrames()
1652   {
1653     if (calculationDialog != null)
1654     {
1655       calculationDialog.closeFrame();
1656     }
1657   }
1658
1659   /**
1660    * hides or shows dynamic annotation rows based on groups and av state flags
1661    */
1662   public void updateAnnotation()
1663   {
1664     updateAnnotation(false, false);
1665   }
1666
1667   public void updateAnnotation(boolean applyGlobalSettings)
1668   {
1669     updateAnnotation(applyGlobalSettings, false);
1670   }
1671
1672   public void updateAnnotation(boolean applyGlobalSettings,
1673           boolean preserveNewGroupSettings)
1674   {
1675     av.updateGroupAnnotationSettings(applyGlobalSettings,
1676             preserveNewGroupSettings);
1677     adjustAnnotationHeight();
1678   }
1679
1680   @Override
1681   public AlignmentI getAlignment()
1682   {
1683     return av == null ? null : av.getAlignment();
1684   }
1685
1686   @Override
1687   public String getViewName()
1688   {
1689     return av.viewName;
1690   }
1691
1692   /**
1693    * Make/Unmake this alignment panel the current input focus
1694    * 
1695    * @param b
1696    */
1697   public void setSelected(boolean b)
1698   {
1699     try
1700     {
1701       if (alignFrame.getSplitViewContainer() != null)
1702       {
1703         /*
1704          * bring enclosing SplitFrame to front first if there is one
1705          */
1706         ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1707       }
1708       alignFrame.setSelected(b);
1709     } catch (Exception ex)
1710     {
1711     }
1712
1713     if (b)
1714     {
1715       alignFrame.setDisplayedView(this);
1716     }
1717   }
1718
1719   @Override
1720   public StructureSelectionManager getStructureSelectionManager()
1721   {
1722     return av.getStructureSelectionManager();
1723   }
1724
1725   @Override
1726   public void raiseOOMWarning(String string, OutOfMemoryError error)
1727   {
1728     new OOMWarning(string, error, this);
1729   }
1730
1731   @Override
1732   public jalview.api.FeatureRenderer cloneFeatureRenderer()
1733   {
1734
1735     return new FeatureRenderer(this);
1736   }
1737
1738   @Override
1739   public jalview.api.FeatureRenderer getFeatureRenderer()
1740   {
1741     return seqPanel.seqCanvas.getFeatureRenderer();
1742   }
1743
1744   public void updateFeatureRenderer(
1745           jalview.renderer.seqfeatures.FeatureRenderer fr)
1746   {
1747     fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1748   }
1749
1750   public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1751   {
1752     if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1753     {
1754       getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1755     }
1756   }
1757
1758   public ScalePanel getScalePanel()
1759   {
1760     return scalePanel;
1761   }
1762
1763   public void setScalePanel(ScalePanel scalePanel)
1764   {
1765     this.scalePanel = scalePanel;
1766   }
1767
1768   public SeqPanel getSeqPanel()
1769   {
1770     return seqPanel;
1771   }
1772
1773   public void setSeqPanel(SeqPanel seqPanel)
1774   {
1775     this.seqPanel = seqPanel;
1776   }
1777
1778   public AnnotationPanel getAnnotationPanel()
1779   {
1780     return annotationPanel;
1781   }
1782
1783   public void setAnnotationPanel(AnnotationPanel annotationPanel)
1784   {
1785     this.annotationPanel = annotationPanel;
1786   }
1787
1788   public AnnotationLabels getAlabels()
1789   {
1790     return alabels;
1791   }
1792
1793   public void setAlabels(AnnotationLabels alabels)
1794   {
1795     this.alabels = alabels;
1796   }
1797
1798   public IdPanel getIdPanel()
1799   {
1800     return idPanel;
1801   }
1802
1803   public void setIdPanel(IdPanel idPanel)
1804   {
1805     this.idPanel = idPanel;
1806   }
1807
1808   /**
1809    * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1810    * The aim is to keep the two alignments 'lined up' on their centre columns.
1811    * 
1812    * @param sr
1813    *          holds mapped region(s) of this alignment that we are scrolling
1814    *          'to'; may be modified for sequence offset by this method
1815    * @param verticalOffset
1816    *          the number of visible sequences to show above the mapped region
1817    */
1818   public void scrollToCentre(SearchResultsI sr, int verticalOffset)
1819   {
1820     /*
1821      * To avoid jumpy vertical scrolling (if some sequences are gapped or not
1822      * mapped), we can make the scroll-to location a sequence above the one
1823      * actually mapped.
1824      */
1825     SequenceI mappedTo = sr.getResults().get(0).getSequence();
1826     List<SequenceI> seqs = av.getAlignment().getSequences();
1827
1828     /*
1829      * This is like AlignmentI.findIndex(seq) but here we are matching the
1830      * dataset sequence not the aligned sequence
1831      */
1832     boolean matched = false;
1833     for (SequenceI seq : seqs)
1834     {
1835       if (mappedTo == seq.getDatasetSequence())
1836       {
1837         matched = true;
1838         break;
1839       }
1840     }
1841     if (!matched)
1842     {
1843       return; // failsafe, shouldn't happen
1844     }
1845
1846     /*
1847      * Scroll to position but centring the target residue.
1848      */
1849     scrollToPosition(sr, verticalOffset, true, true);
1850   }
1851
1852   /**
1853    * Set a flag to say do not scroll any (cDNA/protein) complement.
1854    * 
1855    * @param b
1856    */
1857   protected void setToScrollComplementPanel(boolean b)
1858   {
1859     this.scrollComplementaryPanel = b;
1860   }
1861
1862   /**
1863    * Get whether to scroll complement panel
1864    * 
1865    * @return true if cDNA/protein complement panels should be scrolled
1866    */
1867   protected boolean isSetToScrollComplementPanel()
1868   {
1869     return this.scrollComplementaryPanel;
1870   }
1871
1872   /**
1873    * Redraw sensibly.
1874    * 
1875    * @adjustHeight if true, try to recalculate panel height for visible
1876    *               annotations
1877    */
1878   protected void refresh(boolean adjustHeight)
1879   {
1880     validateAnnotationDimensions(adjustHeight);
1881     addNotify();
1882     if (adjustHeight)
1883     {
1884       // sort, repaint, update overview
1885       paintAlignment(true);
1886     }
1887     else
1888     {
1889       // lightweight repaint
1890       repaint();
1891     }
1892   }
1893
1894   @Override
1895   /**
1896    * Property change event fired when a change is made to the viewport ranges 
1897    * object associated with this alignment panel's viewport
1898    */
1899   public void propertyChange(PropertyChangeEvent evt)
1900   {
1901     // update this panel's scroll values based on the new viewport ranges values
1902     int x = vpRanges.getStartRes();
1903     int y = vpRanges.getStartSeq();
1904     setScrollValues(x, y);
1905
1906     // now update any complementary alignment (its viewport ranges object
1907     // is different so does not get automatically updated)
1908     if (isSetToScrollComplementPanel())
1909     {
1910       setToScrollComplementPanel(false);
1911       av.scrollComplementaryAlignment();
1912       setToScrollComplementPanel(true);
1913     }
1914   }
1915
1916   /**
1917    * Set the reference to the PCA/Tree chooser dialog for this panel. This
1918    * reference should be nulled when the dialog is closed.
1919    * 
1920    * @param calculationChooser
1921    */
1922   public void setCalculationDialog(CalculationChooser calculationChooser)
1923   {
1924     calculationDialog = calculationChooser;
1925   }
1926
1927   /**
1928    * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1929    * if none is open)
1930    */
1931   public CalculationChooser getCalculationDialog()
1932   {
1933     return calculationDialog;
1934   }
1935 }