JAL-2665 Added sequence group update event.
[jalview.git] / src / jalview / gui / SeqCanvas.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.gui;
22
23 import jalview.datamodel.AlignmentI;
24 import jalview.datamodel.HiddenColumns;
25 import jalview.datamodel.SearchResultsI;
26 import jalview.datamodel.SequenceGroup;
27 import jalview.datamodel.SequenceI;
28 import jalview.renderer.ScaleRenderer;
29 import jalview.renderer.ScaleRenderer.ScaleMark;
30 import jalview.viewmodel.ViewportListenerI;
31 import jalview.viewmodel.ViewportRanges;
32
33 import java.awt.AlphaComposite;
34 import java.awt.BasicStroke;
35 import java.awt.BorderLayout;
36 import java.awt.Color;
37 import java.awt.FontMetrics;
38 import java.awt.Graphics;
39 import java.awt.Graphics2D;
40 import java.awt.RenderingHints;
41 import java.awt.Shape;
42 import java.awt.image.BufferedImage;
43 import java.beans.PropertyChangeEvent;
44 import java.util.List;
45
46 import javax.swing.JComponent;
47
48 /**
49  * DOCUMENT ME!
50  * 
51  * @author $author$
52  * @version $Revision$
53  */
54 public class SeqCanvas extends JComponent implements ViewportListenerI
55 {
56   final FeatureRenderer fr;
57
58   final SequenceRenderer sr;
59
60   BufferedImage img;
61
62   Graphics2D gg;
63
64   int imgWidth;
65
66   int imgHeight;
67
68   AlignViewport av;
69
70   boolean fastPaint = false;
71
72   int LABEL_WEST;
73
74   int LABEL_EAST;
75
76   int cursorX = 0;
77
78   int cursorY = 0;
79
80   /**
81    * Creates a new SeqCanvas object.
82    * 
83    * @param av
84    *          DOCUMENT ME!
85    */
86   public SeqCanvas(AlignmentPanel ap)
87   {
88     this.av = ap.av;
89     updateViewport();
90     fr = new FeatureRenderer(ap);
91     sr = new SequenceRenderer(av);
92     setLayout(new BorderLayout());
93     PaintRefresher.Register(this, av.getSequenceSetId());
94     setBackground(Color.white);
95
96     av.getRanges().addPropertyChangeListener(this);
97   }
98
99   public SequenceRenderer getSequenceRenderer()
100   {
101     return sr;
102   }
103
104   public FeatureRenderer getFeatureRenderer()
105   {
106     return fr;
107   }
108
109   int charHeight = 0, charWidth = 0;
110
111   private void updateViewport()
112   {
113     charHeight = av.getCharHeight();
114     charWidth = av.getCharWidth();
115   }
116
117   /**
118    * DOCUMENT ME!
119    * 
120    * @param g
121    *          DOCUMENT ME!
122    * @param startx
123    *          DOCUMENT ME!
124    * @param endx
125    *          DOCUMENT ME!
126    * @param ypos
127    *          DOCUMENT ME!
128    */
129   private void drawNorthScale(Graphics g, int startx, int endx, int ypos)
130   {
131     updateViewport();
132     for (ScaleMark mark : new ScaleRenderer().calculateMarks(av, startx,
133             endx))
134     {
135       int mpos = mark.column; // (i - startx - 1)
136       if (mpos < 0)
137       {
138         continue;
139       }
140       String mstring = mark.text;
141
142       if (mark.major)
143       {
144         if (mstring != null)
145         {
146           g.drawString(mstring, mpos * charWidth, ypos - (charHeight / 2));
147         }
148         g.drawLine((mpos * charWidth) + (charWidth / 2), (ypos + 2)
149                 - (charHeight / 2), (mpos * charWidth) + (charWidth / 2),
150                 ypos - 2);
151       }
152     }
153   }
154
155   /**
156    * DOCUMENT ME!
157    * 
158    * @param g
159    *          DOCUMENT ME!
160    * @param startx
161    *          DOCUMENT ME!
162    * @param endx
163    *          DOCUMENT ME!
164    * @param ypos
165    *          DOCUMENT ME!
166    */
167   void drawWestScale(Graphics g, int startx, int endx, int ypos)
168   {
169     FontMetrics fm = getFontMetrics(av.getFont());
170     ypos += charHeight;
171
172     if (av.hasHiddenColumns())
173     {
174       startx = av.getAlignment().getHiddenColumns()
175               .adjustForHiddenColumns(startx);
176       endx = av.getAlignment().getHiddenColumns()
177               .adjustForHiddenColumns(endx);
178     }
179
180     int maxwidth = av.getAlignment().getWidth();
181     if (av.hasHiddenColumns())
182     {
183       maxwidth = av.getAlignment().getHiddenColumns()
184               .findColumnPosition(maxwidth) - 1;
185     }
186
187     // WEST SCALE
188     for (int i = 0; i < av.getAlignment().getHeight(); i++)
189     {
190       SequenceI seq = av.getAlignment().getSequenceAt(i);
191       int index = startx;
192       int value = -1;
193
194       while (index < endx)
195       {
196         if (jalview.util.Comparison.isGap(seq.getCharAt(index)))
197         {
198           index++;
199
200           continue;
201         }
202
203         value = av.getAlignment().getSequenceAt(i).findPosition(index);
204
205         break;
206       }
207
208       if (value != -1)
209       {
210         int x = LABEL_WEST - fm.stringWidth(String.valueOf(value))
211                 - charWidth / 2;
212         g.drawString(value + "", x, (ypos + (i * charHeight))
213                 - (charHeight / 5));
214       }
215     }
216   }
217
218   /**
219    * DOCUMENT ME!
220    * 
221    * @param g
222    *          DOCUMENT ME!
223    * @param startx
224    *          DOCUMENT ME!
225    * @param endx
226    *          DOCUMENT ME!
227    * @param ypos
228    *          DOCUMENT ME!
229    */
230   void drawEastScale(Graphics g, int startx, int endx, int ypos)
231   {
232     ypos += charHeight;
233
234     if (av.hasHiddenColumns())
235     {
236       endx = av.getAlignment().getHiddenColumns()
237               .adjustForHiddenColumns(endx);
238     }
239
240     SequenceI seq;
241     // EAST SCALE
242     for (int i = 0; i < av.getAlignment().getHeight(); i++)
243     {
244       seq = av.getAlignment().getSequenceAt(i);
245       int index = endx;
246       int value = -1;
247
248       while (index > startx)
249       {
250         if (jalview.util.Comparison.isGap(seq.getCharAt(index)))
251         {
252           index--;
253
254           continue;
255         }
256
257         value = seq.findPosition(index);
258
259         break;
260       }
261
262       if (value != -1)
263       {
264         g.drawString(String.valueOf(value), 0, (ypos + (i * charHeight))
265                 - (charHeight / 5));
266       }
267     }
268   }
269
270   boolean fastpainting = false;
271
272   /**
273    * need to make this thread safe move alignment rendering in response to
274    * slider adjustment
275    * 
276    * @param horizontal
277    *          shift along
278    * @param vertical
279    *          shift up or down in repaint
280    */
281   public void fastPaint(int horizontal, int vertical)
282   {
283     if (fastpainting || gg == null)
284     {
285       return;
286     }
287     fastpainting = true;
288     fastPaint = true;
289     updateViewport();
290
291     ViewportRanges ranges = av.getRanges();
292     int sr = ranges.getStartRes();
293     int er = ranges.getEndRes();
294     int ss = ranges.getStartSeq();
295     int es = ranges.getEndSeq();
296     int transX = 0;
297     int transY = 0;
298
299     gg.copyArea(horizontal * charWidth, vertical * charHeight, imgWidth,
300             imgHeight, -horizontal * charWidth, -vertical * charHeight);
301
302     if (horizontal > 0) // scrollbar pulled right, image to the left
303     {
304       transX = (er - sr - horizontal) * charWidth;
305       sr = er - horizontal;
306     }
307     else if (horizontal < 0)
308     {
309       er = sr - horizontal;
310     }
311     else if (vertical > 0) // scroll down
312     {
313       ss = es - vertical;
314
315       if (ss < ranges.getStartSeq())
316       { // ie scrolling too fast, more than a page at a time
317         ss = ranges.getStartSeq();
318       }
319       else
320       {
321         transY = imgHeight - ((vertical + 1) * charHeight);
322       }
323     }
324     else if (vertical < 0)
325     {
326       es = ss - vertical;
327
328       if (es > ranges.getEndSeq())
329       {
330         es = ranges.getEndSeq();
331       }
332     }
333
334     gg.translate(transX, transY);
335     drawPanel(gg, sr, er, ss, es, 0);
336     gg.translate(-transX, -transY);
337
338     repaint();
339     fastpainting = false;
340   }
341
342   /**
343    * Definitions of startx and endx (hopefully): SMJS This is what I'm working
344    * towards! startx is the first residue (starting at 0) to display. endx is
345    * the last residue to display (starting at 0). starty is the first sequence
346    * to display (starting at 0). endy is the last sequence to display (starting
347    * at 0). NOTE 1: The av limits are set in setFont in this class and in the
348    * adjustment listener in SeqPanel when the scrollbars move.
349    */
350
351   // Set this to false to force a full panel paint
352   @Override
353   public void paintComponent(Graphics g)
354   {
355     updateViewport();
356
357     // img is a cached version of the last view we drew
358     // selectImage will hold any selection we have
359     // lcimg is a local *copy* of img which we'll draw selectImage on top of
360
361     if (img == null)
362     {
363       setupImage();
364     }
365     if (img == null)
366     {
367       return;
368     }
369     BufferedImage lcimg = new BufferedImage(img.getWidth(), img.getHeight(),
370             img.getType());
371     Graphics2D g2d = lcimg.createGraphics();
372     g2d.drawImage(img, 0, 0, null);
373     g2d.dispose();
374
375
376     // BufferedImage lcimg = img; // take reference since other threads may null
377     // img and call later.
378     super.paintComponent(g);
379
380     BufferedImage selectImage = drawSelectionGroup();
381
382     if (lcimg != null
383             && (fastPaint
384                     || (getVisibleRect().width != g.getClipBounds().width) || (getVisibleRect().height != g
385                     .getClipBounds().height)))
386     {
387       Graphics2D g2 = (Graphics2D) lcimg.getGraphics();
388       g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC));
389
390       // overlay selection group on lcimg
391       if (selectImage != null)
392       {
393         g2.setComposite(
394                 AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
395         g2.drawImage(selectImage, 0, 0, this);
396       }
397       g.drawImage(lcimg, 0, 0, this);
398
399       fastPaint = false;
400       return;
401     }
402
403     /*    lcimg = setupImage(lcimg);
404     if (lcimg == null)
405     {
406       return;
407     }*/
408     
409     if (av.antiAlias)
410     {
411       gg.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
412               RenderingHints.VALUE_ANTIALIAS_ON);
413     }
414     
415     gg.setColor(Color.white);
416     gg.fillRect(0, 0, imgWidth, imgHeight);
417     
418     ViewportRanges ranges = av.getRanges();
419     if (av.getWrapAlignment())
420     {
421       drawWrappedPanel(gg, getWidth(), getHeight(), ranges.getStartRes());
422     }
423     else
424     {
425       drawPanel(gg, ranges.getStartRes(), ranges.getEndRes(),
426               ranges.getStartSeq(), ranges.getEndSeq(), 0);
427     }
428
429     Graphics2D g2 = (Graphics2D) lcimg.getGraphics();
430
431     // overlay selection group on lcimg
432     if (selectImage != null)
433     {
434       g2.setComposite(
435               AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
436       g2.drawImage(selectImage, 0, 0, this);
437     }
438     g.drawImage(lcimg, 0, 0, this);
439   }
440
441   private void paintSeqGroup()
442   {
443     fastPaint = true;
444     repaint();
445   }
446
447   private void setupImage()
448   {
449     // this draws the whole of the alignment
450     imgWidth = getWidth();
451     imgHeight = getHeight();
452
453     imgWidth -= (imgWidth % charWidth);
454     imgHeight -= (imgHeight % charHeight);
455
456     if ((imgWidth < 1) || (imgHeight < 1))
457     {
458       return;
459     }
460
461
462       try
463       {
464       img = new BufferedImage(imgWidth, imgHeight,
465                 BufferedImage.TYPE_INT_ARGB); // ARGB so alpha compositing works
466         gg = (Graphics2D) img.getGraphics();
467         gg.setFont(av.getFont());
468       } catch (OutOfMemoryError er)
469       {
470         System.gc();
471         System.err.println("SeqCanvas OutOfMemory Redraw Error.\n" + er);
472         new OOMWarning("Creating alignment image for display", er);
473
474       return;
475       }
476
477   }
478
479   private BufferedImage setupSelectionImage()
480   {
481     BufferedImage lcimg = null;
482
483     int width = getWidth();
484     int height = getHeight();
485
486     width -= (width % charWidth);
487     height -= (height % charHeight);
488
489     if ((width < 1) || (height < 1))
490     {
491       return null;
492     }
493
494     try
495     {
496       lcimg = new BufferedImage(width, height,
497               BufferedImage.TYPE_INT_ARGB); // ARGB so alpha compositing works
498     } catch (OutOfMemoryError er)
499     {
500       System.gc();
501       System.err.println(
502               "Selection Group image OutOfMemory Redraw Error.\n" + er);
503       new OOMWarning("Creating alignment image for display", er);
504
505       return null;
506     }
507
508     return lcimg;
509   }
510
511   /**
512    * DOCUMENT ME!
513    * 
514    * @param cwidth
515    *          DOCUMENT ME!
516    * 
517    * @return DOCUMENT ME!
518    */
519   public int getWrappedCanvasWidth(int cwidth)
520   {
521     FontMetrics fm = getFontMetrics(av.getFont());
522
523     LABEL_EAST = 0;
524     LABEL_WEST = 0;
525
526     if (av.getScaleRightWrapped())
527     {
528       LABEL_EAST = fm.stringWidth(getMask());
529     }
530
531     if (av.getScaleLeftWrapped())
532     {
533       LABEL_WEST = fm.stringWidth(getMask());
534     }
535
536     return (cwidth - LABEL_EAST - LABEL_WEST) / charWidth;
537   }
538
539   /**
540    * Generates a string of zeroes.
541    * 
542    * @return String
543    */
544   String getMask()
545   {
546     String mask = "00";
547     int maxWidth = 0;
548     int tmp;
549     for (int i = 0; i < av.getAlignment().getHeight(); i++)
550     {
551       tmp = av.getAlignment().getSequenceAt(i).getEnd();
552       if (tmp > maxWidth)
553       {
554         maxWidth = tmp;
555       }
556     }
557
558     for (int i = maxWidth; i > 0; i /= 10)
559     {
560       mask += "0";
561     }
562     return mask;
563   }
564
565   /**
566    * DOCUMENT ME!
567    * 
568    * @param g
569    *          DOCUMENT ME!
570    * @param canvasWidth
571    *          DOCUMENT ME!
572    * @param canvasHeight
573    *          DOCUMENT ME!
574    * @param startRes
575    *          DOCUMENT ME!
576    */
577   public void drawWrappedPanel(Graphics g, int canvasWidth,
578           int canvasHeight, int startRes)
579   {
580     updateViewport();
581     AlignmentI al = av.getAlignment();
582
583     FontMetrics fm = getFontMetrics(av.getFont());
584
585     LABEL_EAST = 0;
586     LABEL_WEST = 0;
587
588     if (av.getScaleRightWrapped())
589     {
590       LABEL_EAST = fm.stringWidth(getMask());
591     }
592
593     if (av.getScaleLeftWrapped())
594     {
595       LABEL_WEST = fm.stringWidth(getMask());
596     }
597
598     int hgap = charHeight;
599     if (av.getScaleAboveWrapped())
600     {
601       hgap += charHeight;
602     }
603
604     int cWidth = (canvasWidth - LABEL_EAST - LABEL_WEST) / charWidth;
605     int cHeight = av.getAlignment().getHeight() * charHeight;
606
607     av.setWrappedWidth(cWidth);
608
609     av.getRanges().setViewportStartAndWidth(startRes, cWidth);
610
611     int endx;
612     int ypos = hgap;
613     int maxwidth = av.getAlignment().getWidth();
614
615     if (av.hasHiddenColumns())
616     {
617       maxwidth = av.getAlignment().getHiddenColumns()
618               .findColumnPosition(maxwidth);
619     }
620
621     while ((ypos <= canvasHeight) && (startRes < maxwidth))
622     {
623       endx = startRes + cWidth - 1;
624
625       if (endx > maxwidth)
626       {
627         endx = maxwidth;
628       }
629
630       g.setFont(av.getFont());
631       g.setColor(Color.black);
632
633       if (av.getScaleLeftWrapped())
634       {
635         drawWestScale(g, startRes, endx, ypos);
636       }
637
638       if (av.getScaleRightWrapped())
639       {
640         g.translate(canvasWidth - LABEL_EAST, 0);
641         drawEastScale(g, startRes, endx, ypos);
642         g.translate(-(canvasWidth - LABEL_EAST), 0);
643       }
644
645       g.translate(LABEL_WEST, 0);
646
647       if (av.getScaleAboveWrapped())
648       {
649         drawNorthScale(g, startRes, endx, ypos);
650       }
651
652       if (av.hasHiddenColumns() && av.getShowHiddenMarkers())
653       {
654         g.setColor(Color.blue);
655         int res;
656         HiddenColumns hidden = av.getAlignment().getHiddenColumns();
657         List<Integer> positions = hidden.findHiddenRegionPositions();
658         for (int pos : positions)
659         {
660           res = pos - startRes;
661
662           if (res < 0 || res > endx - startRes)
663           {
664             continue;
665           }
666
667           gg.fillPolygon(
668                   new int[] { res * charWidth - charHeight / 4,
669                       res * charWidth + charHeight / 4, res * charWidth },
670                   new int[] { ypos - (charHeight / 2),
671                       ypos - (charHeight / 2), ypos - (charHeight / 2) + 8 },
672                   3);
673
674         }
675       }
676
677       // When printing we have an extra clipped region,
678       // the Printable page which we need to account for here
679       Shape clip = g.getClip();
680
681       if (clip == null)
682       {
683         g.setClip(0, 0, cWidth * charWidth, canvasHeight);
684       }
685       else
686       {
687         g.setClip(0, (int) clip.getBounds().getY(), cWidth * charWidth,
688                 (int) clip.getBounds().getHeight());
689       }
690
691       drawPanel(g, startRes, endx, 0, al.getHeight() - 1, ypos);
692
693       if (av.isShowAnnotation())
694       {
695         g.translate(0, cHeight + ypos + 3);
696         if (annotations == null)
697         {
698           annotations = new AnnotationPanel(av);
699         }
700
701         annotations.renderer.drawComponent(annotations, av, g, -1,
702                 startRes, endx + 1);
703         g.translate(0, -cHeight - ypos - 3);
704       }
705       g.setClip(clip);
706       g.translate(-LABEL_WEST, 0);
707
708       ypos += cHeight + getAnnotationHeight() + hgap;
709
710       startRes += cWidth;
711     }
712   }
713
714   AnnotationPanel annotations;
715
716   int getAnnotationHeight()
717   {
718     if (!av.isShowAnnotation())
719     {
720       return 0;
721     }
722
723     if (annotations == null)
724     {
725       annotations = new AnnotationPanel(av);
726     }
727
728     return annotations.adjustPanelHeight();
729   }
730
731   /**
732    * DOCUMENT ME!
733    * 
734    * @param g1
735    *          DOCUMENT ME!
736    * @param startRes
737    *          DOCUMENT ME!
738    * @param endRes
739    *          DOCUMENT ME!
740    * @param startSeq
741    *          DOCUMENT ME!
742    * @param endSeq
743    *          DOCUMENT ME!
744    * @param offset
745    *          DOCUMENT ME!
746    */
747   public void drawPanel(Graphics g1, int startRes, int endRes,
748           int startSeq, int endSeq, int offset)
749   {
750     updateViewport();
751     if (!av.hasHiddenColumns())
752     {
753       draw(g1, startRes, endRes, startSeq, endSeq, offset);
754     }
755     else
756     {
757       int screenY = 0;
758       int blockStart = startRes;
759       int blockEnd = endRes;
760
761       for (int[] region : av.getAlignment().getHiddenColumns()
762               .getHiddenColumnsCopy())
763       {
764         int hideStart = region[0];
765         int hideEnd = region[1];
766
767         if (hideStart <= blockStart)
768         {
769           blockStart += (hideEnd - hideStart) + 1;
770           continue;
771         }
772
773         blockEnd = hideStart - 1;
774
775         g1.translate(screenY * charWidth, 0);
776
777         draw(g1, blockStart, blockEnd, startSeq, endSeq, offset);
778
779         if (av.getShowHiddenMarkers())
780         {
781           g1.setColor(Color.blue);
782
783           g1.drawLine((blockEnd - blockStart + 1) * charWidth - 1,
784                   0 + offset, (blockEnd - blockStart + 1) * charWidth - 1,
785                   (endSeq - startSeq + 1) * charHeight + offset);
786         }
787
788         g1.translate(-screenY * charWidth, 0);
789         screenY += blockEnd - blockStart + 1;
790         blockStart = hideEnd + 1;
791
792         if (screenY > (endRes - startRes))
793         {
794           // already rendered last block
795           return;
796         }
797       }
798
799       if (screenY <= (endRes - startRes))
800       {
801         // remaining visible region to render
802         blockEnd = blockStart + (endRes - startRes) - screenY;
803         g1.translate(screenY * charWidth, 0);
804         draw(g1, blockStart, blockEnd, startSeq, endSeq, offset);
805
806         g1.translate(-screenY * charWidth, 0);
807       }
808     }
809
810   }
811
812   // int startRes, int endRes, int startSeq, int endSeq, int x, int y,
813   // int x1, int x2, int y1, int y2, int startx, int starty,
814   private void draw(Graphics g, int startRes, int endRes, int startSeq,
815           int endSeq, int offset)
816   {
817     g.setFont(av.getFont());
818     sr.prepare(g, av.isRenderGaps());
819
820     SequenceI nextSeq;
821
822     // / First draw the sequences
823     // ///////////////////////////
824     for (int i = startSeq; i <= endSeq; i++)
825     {
826       nextSeq = av.getAlignment().getSequenceAt(i);
827       if (nextSeq == null)
828       {
829         // occasionally, a race condition occurs such that the alignment row is
830         // empty
831         continue;
832       }
833       sr.drawSequence(nextSeq, av.getAlignment().findAllGroups(nextSeq),
834               startRes, endRes, offset + ((i - startSeq) * charHeight));
835
836       if (av.isShowSequenceFeatures())
837       {
838         fr.drawSequence(g, nextSeq, startRes, endRes, offset
839                 + ((i - startSeq) * charHeight), false);
840       }
841
842       // / Highlight search Results once all sequences have been drawn
843       // ////////////////////////////////////////////////////////
844       if (av.hasSearchResults())
845       {
846         int[] visibleResults = av.getSearchResults().getResults(nextSeq,
847                 startRes, endRes);
848         if (visibleResults != null)
849         {
850           for (int r = 0; r < visibleResults.length; r += 2)
851           {
852             sr.drawHighlightedText(nextSeq, visibleResults[r],
853                     visibleResults[r + 1], (visibleResults[r] - startRes)
854                             * charWidth, offset
855                             + ((i - startSeq) * charHeight));
856           }
857         }
858       }
859
860       if (av.cursorMode && cursorY == i && cursorX >= startRes
861               && cursorX <= endRes)
862       {
863         sr.drawCursor(nextSeq, cursorX, (cursorX - startRes) * charWidth,
864                 offset + ((i - startSeq) * charHeight));
865       }
866     }
867
868     if (av.getSelectionGroup() != null
869             || av.getAlignment().getGroups().size() > 0)
870     {
871       drawGroupsBoundaries(g, startRes, endRes, startSeq, endSeq, offset);
872     }
873
874   }
875
876   void drawGroupsBoundaries(Graphics g1, int startRes, int endRes,
877           int startSeq, int endSeq, int offset)
878   {
879     Graphics2D g = (Graphics2D) g1;
880     //
881     // ///////////////////////////////////
882     // Now outline any areas if necessary
883     // ///////////////////////////////////
884
885     SequenceGroup group = null;
886
887     int sx = -1;
888     int sy = -1;
889     int ex = -1;
890     int groupIndex = -1;
891     int visWidth = (endRes - startRes + 1) * charWidth;
892
893     if (av.getAlignment().getGroups().size() > 0)
894     {
895       group = av.getAlignment().getGroups().get(0);
896       groupIndex = 0;
897     }
898
899     if (group != null)
900     {
901       do
902       {
903         int oldY = -1;
904         int i = 0;
905         boolean inGroup = false;
906         int top = -1;
907         int bottom = -1;
908
909         for (i = startSeq; i <= endSeq; i++)
910         {
911           // position of start residue of group relative to startRes, in pixels
912           sx = (group.getStartRes() - startRes) * charWidth;
913           sy = offset + ((i - startSeq) * charHeight);
914           // width of group in pixels
915           ex = (((group.getEndRes() + 1) - group.getStartRes()) * charWidth) - 1;
916
917           if (sx + ex < 0 || sx > visWidth)
918           {
919             continue;
920           }
921
922           if ((sx <= (endRes - startRes) * charWidth)
923                   && group.getSequences(null).contains(
924                           av.getAlignment().getSequenceAt(i)))
925           {
926             if ((bottom == -1)
927                     && !group.getSequences(null).contains(
928                             av.getAlignment().getSequenceAt(i + 1)))
929             {
930               bottom = sy + charHeight;
931             }
932
933             if (!inGroup)
934             {
935               if (((top == -1) && (i == 0))
936                       || !group.getSequences(null).contains(
937                               av.getAlignment().getSequenceAt(i - 1)))
938               {
939                 top = sy;
940               }
941
942               oldY = sy;
943               inGroup = true;
944
945               g.setStroke(new BasicStroke());
946               g.setColor(group.getOutlineColour());
947             }
948           }
949           else
950           {
951             if (inGroup)
952             {
953               // if start position is visible, draw vertical line to left of
954               // group
955               if (sx >= 0 && sx < visWidth)
956               {
957                 g.drawLine(sx, oldY, sx, sy);
958               }
959
960               // if end position is visible, draw vertical line to right of
961               // group
962               if (sx + ex < visWidth)
963               {
964                 g.drawLine(sx + ex, oldY, sx + ex, sy);
965               }
966
967               if (sx < 0)
968               {
969                 // ex += sx;
970                 // sx = 0;
971               }
972
973               if (sx + ex > visWidth)
974               {
975                 ex = visWidth;
976               }
977
978               else if (sx + ex >= (endRes - startRes + 1) * charWidth)
979               {
980                 ex = (endRes - startRes + 1) * charWidth;
981               }
982
983               // draw horizontal line at top of group
984               if (top != -1)
985               {
986                 g.drawLine(sx, top, sx + ex, top);
987                 top = -1;
988               }
989
990               // draw horizontal line at bottom of group
991               if (bottom != -1)
992               {
993                 g.drawLine(sx, bottom, sx + ex, bottom);
994                 bottom = -1;
995               }
996
997               inGroup = false;
998             }
999           }
1000         }
1001
1002         if (inGroup)
1003         {
1004           sy = offset + ((i - startSeq) * charHeight);
1005           if (sx >= 0 && sx < visWidth)
1006           {
1007             g.drawLine(sx, oldY, sx, sy);
1008           }
1009
1010           if (sx + ex < visWidth)
1011           {
1012             g.drawLine(sx + ex, oldY, sx + ex, sy);
1013           }
1014
1015           if (sx < 0)
1016           {
1017             ex += sx;
1018             sx = 0;
1019           }
1020
1021           if (sx + ex > visWidth)
1022           {
1023             ex = visWidth;
1024           }
1025           else if (sx + ex >= (endRes - startRes + 1) * charWidth)
1026           {
1027             ex = (endRes - startRes + 1) * charWidth;
1028           }
1029
1030           if (top != -1)
1031           {
1032             g.drawLine(sx, top, sx + ex, top);
1033             top = -1;
1034           }
1035
1036           if (bottom != -1)
1037           {
1038             g.drawLine(sx, bottom - 1, sx + ex, bottom - 1);
1039             bottom = -1;
1040           }
1041
1042           inGroup = false;
1043         }
1044
1045         groupIndex++;
1046
1047         g.setStroke(new BasicStroke());
1048
1049         if (groupIndex >= av.getAlignment().getGroups().size())
1050         {
1051           break;
1052         }
1053
1054         group = av.getAlignment().getGroups().get(groupIndex);
1055
1056       } while (groupIndex < av.getAlignment().getGroups().size());
1057
1058     }
1059
1060   }
1061
1062   /*
1063    * Draw the selection group as a separate image and overlay
1064    */
1065   private BufferedImage drawSelectionGroup()
1066   {
1067     // get a new image of the correct size
1068     BufferedImage selectionImage = setupSelectionImage();
1069
1070     if (selectionImage == null)
1071     {
1072       return null;
1073     }
1074
1075     SequenceGroup group = av.getSelectionGroup();
1076     if (group == null)
1077     {
1078       // nothing to draw
1079       return null;
1080     }
1081
1082     // set up drawing colour
1083     Graphics2D g = (Graphics2D) selectionImage.getGraphics();
1084     // set background to transparent
1085     g.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f));
1086     g.fillRect(0, 0, selectionImage.getWidth(), selectionImage.getHeight());
1087
1088     g.setComposite(AlphaComposite.Src);
1089     g.setStroke(new BasicStroke(1, BasicStroke.CAP_BUTT,
1090             BasicStroke.JOIN_ROUND, 3f, new float[]
1091     { 5f, 3f }, 0f));
1092     g.setColor(Color.RED);
1093
1094     int visWidth = av.getRanges().getViewportWidth() * charWidth;
1095
1096     int startRes = av.getRanges().getStartRes();
1097
1098     // set x start and end positions of group
1099     int startx = (group.getStartRes() - startRes) * charWidth;
1100     int endx = (group.getEndRes() - startRes + 1) * charWidth;
1101
1102     int oldY = -1;
1103     int i = 0;
1104     boolean inGroup = false;
1105     int top = -1;
1106     int bottom = -1;
1107
1108     // get sequences to determine y positions of group
1109     int startSeq = av.getRanges().getStartSeq();
1110     for (i = startSeq; i <= av.getRanges().getEndSeq(); ++i)
1111     {
1112       int sy = (i - startSeq) * charHeight;
1113
1114       if (group.getSequences(null)
1115               .contains(av.getAlignment().getSequenceAt(i)))
1116       {
1117         if ((bottom == -1) && !group.getSequences(null)
1118                 .contains(av.getAlignment().getSequenceAt(i + 1)))
1119         {
1120           bottom = sy + charHeight;
1121         }
1122
1123         if (!inGroup)
1124         {
1125           if (((top == -1) && (i == 0)) || !group.getSequences(null)
1126                   .contains(av.getAlignment().getSequenceAt(i - 1)))
1127           {
1128             top = sy;
1129           }
1130
1131           oldY = sy;
1132           inGroup = true;
1133         }
1134       }
1135       else
1136       {
1137         if (inGroup)
1138         {
1139           // if start position is visible, draw vertical line to left of
1140           // group
1141           if (startx >= 0 && startx < visWidth * charWidth)
1142           {
1143             g.drawLine(startx, oldY, startx, sy);
1144           }
1145
1146           // if end position is visible, draw vertical line to right of
1147           // group
1148           if (endx <= visWidth * charWidth)
1149           {
1150             g.drawLine(endx, oldY, endx, sy);
1151           }
1152
1153           if (endx > visWidth * charWidth)
1154           {
1155             endx = visWidth * charWidth;
1156           }
1157
1158           // draw horizontal line at top of group
1159           if (top != -1)
1160           {
1161             g.drawLine(startx, top, endx, top);
1162             top = -1;
1163           }
1164
1165           // draw horizontal line at bottom of group
1166           if (bottom != -1)
1167           {
1168             g.drawLine(startx, bottom, endx, bottom);
1169             bottom = -1;
1170           }
1171
1172           inGroup = false;
1173         }
1174       }
1175     }
1176     if (inGroup)
1177     {
1178       int sy = (i - startSeq) * charHeight;
1179       if (startx >= 0 && startx < visWidth)
1180       {
1181         g.drawLine(startx, oldY, startx, sy);
1182       }
1183
1184       if (endx < visWidth)
1185       {
1186         g.drawLine(endx, oldY, endx, sy);
1187       }
1188
1189       if (endx > visWidth)
1190       {
1191         endx = visWidth;
1192       }
1193
1194       if (top != -1)
1195       {
1196         g.drawLine(startx, top, endx, top);
1197         top = -1;
1198       }
1199
1200       if (bottom != -1)
1201       {
1202         g.drawLine(startx, bottom - 1, endx, bottom - 1);
1203         bottom = -1;
1204       }
1205
1206       inGroup = false;
1207     }
1208
1209     return selectionImage;
1210   }
1211
1212   /**
1213    * DOCUMENT ME!
1214    * 
1215    * @param results
1216    *          DOCUMENT ME!
1217    */
1218   public void highlightSearchResults(SearchResultsI results)
1219   {
1220     img = null;
1221
1222     av.setSearchResults(results);
1223
1224     repaint();
1225   }
1226
1227   @Override
1228   public void propertyChange(PropertyChangeEvent evt)
1229   {
1230     String eventName = evt.getPropertyName();
1231
1232     if (eventName.equals(SequenceGroup.SEQ_GROUP_CHANGED))
1233     {
1234       paintSeqGroup();
1235     }
1236     else if (av.getWrapAlignment())
1237     {
1238       if (eventName.equals(ViewportRanges.STARTRES))
1239       {
1240         repaint();
1241       }
1242     }
1243     else
1244     {
1245       int scrollX = 0;
1246       if (eventName.equals(ViewportRanges.STARTRES))
1247       {
1248         // Make sure we're not trying to draw a panel
1249         // larger than the visible window
1250         ViewportRanges vpRanges = av.getRanges();
1251         scrollX = (int) evt.getNewValue() - (int) evt.getOldValue();
1252         int range = vpRanges.getEndRes() - vpRanges.getStartRes();
1253         if (scrollX > range)
1254         {
1255           scrollX = range;
1256         }
1257         else if (scrollX < -range)
1258         {
1259           scrollX = -range;
1260         }
1261       }
1262
1263       // Both scrolling and resizing change viewport ranges: scrolling changes
1264       // both start and end points, but resize only changes end values.
1265       // Here we only want to fastpaint on a scroll, with resize using a normal
1266       // paint, so scroll events are identified as changes to the horizontal or
1267       // vertical start value.
1268       if (eventName.equals(ViewportRanges.STARTRES))
1269       {
1270         // scroll - startres and endres both change
1271         fastPaint(scrollX, 0);
1272       }
1273       else if (eventName.equals(ViewportRanges.STARTSEQ))
1274       {
1275         // scroll
1276         fastPaint(0, (int) evt.getNewValue() - (int) evt.getOldValue());
1277       }
1278     }
1279   }
1280 }