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