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