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