JAL-2665 Draw selection group - works on scroll but not when static
[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     BufferedImage lcimg = img; // take reference since other threads may null
357     // img and call later.
358     super.paintComponent(g);
359
360     BufferedImage selectImage = drawSelectionGroup();
361
362     if (lcimg != null
363             && (fastPaint
364                     || (getVisibleRect().width != g.getClipBounds().width) || (getVisibleRect().height != g
365                     .getClipBounds().height)))
366     {
367       Graphics2D g2 = (Graphics2D) lcimg.getGraphics();
368       g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC));
369       // g.drawImage(lcimg, 0, 0, this);
370
371       // overlay selection group on lcimg
372       if (selectImage != null)
373       {
374         g2.setComposite(
375                 AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
376         g2.drawImage(selectImage, 0, 0, this);
377       }
378       g.drawImage(lcimg, 0, 0, this);
379
380       fastPaint = false;
381       return;
382     }
383
384     lcimg = setupImage(lcimg);
385     // img = lcimg;
386     if (lcimg == null)
387     {
388       return;
389     }
390     
391     if (av.antiAlias)
392     {
393       gg.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
394               RenderingHints.VALUE_ANTIALIAS_ON);
395     }
396     
397     gg.setColor(Color.white);
398     gg.fillRect(0, 0, imgWidth, imgHeight);
399     
400     ViewportRanges ranges = av.getRanges();
401     if (av.getWrapAlignment())
402     {
403       drawWrappedPanel(gg, getWidth(), getHeight(), ranges.getStartRes());
404     }
405     else
406     {
407       drawPanel(gg, ranges.getStartRes(), ranges.getEndRes(),
408               ranges.getStartSeq(), ranges.getEndSeq(), 0);
409     }
410
411     Graphics2D g2 = (Graphics2D) lcimg.getGraphics();
412     // g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC));
413     // g.drawImage(lcimg, 0, 0, this); // scrolling only works with g not g2???
414
415     // overlay selection group on lcimg
416     if (selectImage != null)
417     {
418       g2.setComposite(
419               AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
420       g2.drawImage(selectImage, 0, 0, this);
421     }
422     g.drawImage(lcimg, 0, 0, this);
423     // g.drawImage(selectImage, 0, 0, this);
424   }
425
426   private BufferedImage setupImage(BufferedImage lcimg)
427   {
428     // this draws the whole of the alignment
429     imgWidth = getWidth();
430     imgHeight = getHeight();
431
432     imgWidth -= (imgWidth % charWidth);
433     imgHeight -= (imgHeight % charHeight);
434
435     if ((imgWidth < 1) || (imgHeight < 1))
436     {
437       return null;
438     }
439
440     if (lcimg == null || imgWidth != lcimg.getWidth()
441             || imgHeight != lcimg.getHeight())
442     {
443       try
444       {
445         lcimg = img = new BufferedImage(imgWidth, imgHeight,
446                 BufferedImage.TYPE_INT_ARGB); // ARGB so alpha compositing works
447         gg = (Graphics2D) img.getGraphics();
448         gg.setFont(av.getFont());
449       } catch (OutOfMemoryError er)
450       {
451         System.gc();
452         System.err.println("SeqCanvas OutOfMemory Redraw Error.\n" + er);
453         new OOMWarning("Creating alignment image for display", er);
454
455         return null;
456       }
457     }
458     return lcimg;
459   }
460
461   private BufferedImage setupSelectionImage()
462   {
463     BufferedImage lcimg = null;
464
465     int width = getWidth();
466     int height = getHeight();
467
468     width -= (width % charWidth);
469     height -= (height % charHeight);
470
471     if ((width < 1) || (height < 1))
472     {
473       return null;
474     }
475
476     try
477     {
478       lcimg = new BufferedImage(imgWidth, imgHeight,
479               BufferedImage.TYPE_INT_ARGB); // ARGB so alpha compositing works
480     } catch (OutOfMemoryError er)
481     {
482       System.gc();
483       System.err.println(
484               "Selection Group image OutOfMemory Redraw Error.\n" + er);
485       new OOMWarning("Creating alignment image for display", er);
486
487       return null;
488     }
489
490     return lcimg;
491   }
492
493   /**
494    * DOCUMENT ME!
495    * 
496    * @param cwidth
497    *          DOCUMENT ME!
498    * 
499    * @return DOCUMENT ME!
500    */
501   public int getWrappedCanvasWidth(int cwidth)
502   {
503     FontMetrics fm = getFontMetrics(av.getFont());
504
505     LABEL_EAST = 0;
506     LABEL_WEST = 0;
507
508     if (av.getScaleRightWrapped())
509     {
510       LABEL_EAST = fm.stringWidth(getMask());
511     }
512
513     if (av.getScaleLeftWrapped())
514     {
515       LABEL_WEST = fm.stringWidth(getMask());
516     }
517
518     return (cwidth - LABEL_EAST - LABEL_WEST) / charWidth;
519   }
520
521   /**
522    * Generates a string of zeroes.
523    * 
524    * @return String
525    */
526   String getMask()
527   {
528     String mask = "00";
529     int maxWidth = 0;
530     int tmp;
531     for (int i = 0; i < av.getAlignment().getHeight(); i++)
532     {
533       tmp = av.getAlignment().getSequenceAt(i).getEnd();
534       if (tmp > maxWidth)
535       {
536         maxWidth = tmp;
537       }
538     }
539
540     for (int i = maxWidth; i > 0; i /= 10)
541     {
542       mask += "0";
543     }
544     return mask;
545   }
546
547   /**
548    * DOCUMENT ME!
549    * 
550    * @param g
551    *          DOCUMENT ME!
552    * @param canvasWidth
553    *          DOCUMENT ME!
554    * @param canvasHeight
555    *          DOCUMENT ME!
556    * @param startRes
557    *          DOCUMENT ME!
558    */
559   public void drawWrappedPanel(Graphics g, int canvasWidth,
560           int canvasHeight, int startRes)
561   {
562     updateViewport();
563     AlignmentI al = av.getAlignment();
564
565     FontMetrics fm = getFontMetrics(av.getFont());
566
567     LABEL_EAST = 0;
568     LABEL_WEST = 0;
569
570     if (av.getScaleRightWrapped())
571     {
572       LABEL_EAST = fm.stringWidth(getMask());
573     }
574
575     if (av.getScaleLeftWrapped())
576     {
577       LABEL_WEST = fm.stringWidth(getMask());
578     }
579
580     int hgap = charHeight;
581     if (av.getScaleAboveWrapped())
582     {
583       hgap += charHeight;
584     }
585
586     int cWidth = (canvasWidth - LABEL_EAST - LABEL_WEST) / charWidth;
587     int cHeight = av.getAlignment().getHeight() * charHeight;
588
589     av.setWrappedWidth(cWidth);
590
591     av.getRanges().setViewportStartAndWidth(startRes, cWidth);
592
593     int endx;
594     int ypos = hgap;
595     int maxwidth = av.getAlignment().getWidth();
596
597     if (av.hasHiddenColumns())
598     {
599       maxwidth = av.getAlignment().getHiddenColumns()
600               .findColumnPosition(maxwidth);
601     }
602
603     while ((ypos <= canvasHeight) && (startRes < maxwidth))
604     {
605       endx = startRes + cWidth - 1;
606
607       if (endx > maxwidth)
608       {
609         endx = maxwidth;
610       }
611
612       g.setFont(av.getFont());
613       g.setColor(Color.black);
614
615       if (av.getScaleLeftWrapped())
616       {
617         drawWestScale(g, startRes, endx, ypos);
618       }
619
620       if (av.getScaleRightWrapped())
621       {
622         g.translate(canvasWidth - LABEL_EAST, 0);
623         drawEastScale(g, startRes, endx, ypos);
624         g.translate(-(canvasWidth - LABEL_EAST), 0);
625       }
626
627       g.translate(LABEL_WEST, 0);
628
629       if (av.getScaleAboveWrapped())
630       {
631         drawNorthScale(g, startRes, endx, ypos);
632       }
633
634       if (av.hasHiddenColumns() && av.getShowHiddenMarkers())
635       {
636         g.setColor(Color.blue);
637         int res;
638         HiddenColumns hidden = av.getAlignment().getHiddenColumns();
639         List<Integer> positions = hidden.findHiddenRegionPositions();
640         for (int pos : positions)
641         {
642           res = pos - startRes;
643
644           if (res < 0 || res > endx - startRes)
645           {
646             continue;
647           }
648
649           gg.fillPolygon(
650                   new int[] { res * charWidth - charHeight / 4,
651                       res * charWidth + charHeight / 4, res * charWidth },
652                   new int[] { ypos - (charHeight / 2),
653                       ypos - (charHeight / 2), ypos - (charHeight / 2) + 8 },
654                   3);
655
656         }
657       }
658
659       // When printing we have an extra clipped region,
660       // the Printable page which we need to account for here
661       Shape clip = g.getClip();
662
663       if (clip == null)
664       {
665         g.setClip(0, 0, cWidth * charWidth, canvasHeight);
666       }
667       else
668       {
669         g.setClip(0, (int) clip.getBounds().getY(), cWidth * charWidth,
670                 (int) clip.getBounds().getHeight());
671       }
672
673       drawPanel(g, startRes, endx, 0, al.getHeight() - 1, ypos);
674
675       if (av.isShowAnnotation())
676       {
677         g.translate(0, cHeight + ypos + 3);
678         if (annotations == null)
679         {
680           annotations = new AnnotationPanel(av);
681         }
682
683         annotations.renderer.drawComponent(annotations, av, g, -1,
684                 startRes, endx + 1);
685         g.translate(0, -cHeight - ypos - 3);
686       }
687       g.setClip(clip);
688       g.translate(-LABEL_WEST, 0);
689
690       ypos += cHeight + getAnnotationHeight() + hgap;
691
692       startRes += cWidth;
693     }
694   }
695
696   AnnotationPanel annotations;
697
698   int getAnnotationHeight()
699   {
700     if (!av.isShowAnnotation())
701     {
702       return 0;
703     }
704
705     if (annotations == null)
706     {
707       annotations = new AnnotationPanel(av);
708     }
709
710     return annotations.adjustPanelHeight();
711   }
712
713   /**
714    * DOCUMENT ME!
715    * 
716    * @param g1
717    *          DOCUMENT ME!
718    * @param startRes
719    *          DOCUMENT ME!
720    * @param endRes
721    *          DOCUMENT ME!
722    * @param startSeq
723    *          DOCUMENT ME!
724    * @param endSeq
725    *          DOCUMENT ME!
726    * @param offset
727    *          DOCUMENT ME!
728    */
729   public void drawPanel(Graphics g1, int startRes, int endRes,
730           int startSeq, int endSeq, int offset)
731   {
732     updateViewport();
733     if (!av.hasHiddenColumns())
734     {
735       draw(g1, startRes, endRes, startSeq, endSeq, offset);
736     }
737     else
738     {
739       int screenY = 0;
740       int blockStart = startRes;
741       int blockEnd = endRes;
742
743       for (int[] region : av.getAlignment().getHiddenColumns()
744               .getHiddenColumnsCopy())
745       {
746         int hideStart = region[0];
747         int hideEnd = region[1];
748
749         if (hideStart <= blockStart)
750         {
751           blockStart += (hideEnd - hideStart) + 1;
752           continue;
753         }
754
755         blockEnd = hideStart - 1;
756
757         g1.translate(screenY * charWidth, 0);
758
759         draw(g1, blockStart, blockEnd, startSeq, endSeq, offset);
760
761         if (av.getShowHiddenMarkers())
762         {
763           g1.setColor(Color.blue);
764
765           g1.drawLine((blockEnd - blockStart + 1) * charWidth - 1,
766                   0 + offset, (blockEnd - blockStart + 1) * charWidth - 1,
767                   (endSeq - startSeq + 1) * charHeight + offset);
768         }
769
770         g1.translate(-screenY * charWidth, 0);
771         screenY += blockEnd - blockStart + 1;
772         blockStart = hideEnd + 1;
773
774         if (screenY > (endRes - startRes))
775         {
776           // already rendered last block
777           return;
778         }
779       }
780
781       if (screenY <= (endRes - startRes))
782       {
783         // remaining visible region to render
784         blockEnd = blockStart + (endRes - startRes) - screenY;
785         g1.translate(screenY * charWidth, 0);
786         draw(g1, blockStart, blockEnd, startSeq, endSeq, offset);
787
788         g1.translate(-screenY * charWidth, 0);
789       }
790     }
791
792   }
793
794   // int startRes, int endRes, int startSeq, int endSeq, int x, int y,
795   // int x1, int x2, int y1, int y2, int startx, int starty,
796   private void draw(Graphics g, int startRes, int endRes, int startSeq,
797           int endSeq, int offset)
798   {
799     g.setFont(av.getFont());
800     sr.prepare(g, av.isRenderGaps());
801
802     SequenceI nextSeq;
803
804     // / First draw the sequences
805     // ///////////////////////////
806     for (int i = startSeq; i <= endSeq; i++)
807     {
808       nextSeq = av.getAlignment().getSequenceAt(i);
809       if (nextSeq == null)
810       {
811         // occasionally, a race condition occurs such that the alignment row is
812         // empty
813         continue;
814       }
815       sr.drawSequence(nextSeq, av.getAlignment().findAllGroups(nextSeq),
816               startRes, endRes, offset + ((i - startSeq) * charHeight));
817
818       if (av.isShowSequenceFeatures())
819       {
820         fr.drawSequence(g, nextSeq, startRes, endRes, offset
821                 + ((i - startSeq) * charHeight), false);
822       }
823
824       // / Highlight search Results once all sequences have been drawn
825       // ////////////////////////////////////////////////////////
826       if (av.hasSearchResults())
827       {
828         int[] visibleResults = av.getSearchResults().getResults(nextSeq,
829                 startRes, endRes);
830         if (visibleResults != null)
831         {
832           for (int r = 0; r < visibleResults.length; r += 2)
833           {
834             sr.drawHighlightedText(nextSeq, visibleResults[r],
835                     visibleResults[r + 1], (visibleResults[r] - startRes)
836                             * charWidth, offset
837                             + ((i - startSeq) * charHeight));
838           }
839         }
840       }
841
842       if (av.cursorMode && cursorY == i && cursorX >= startRes
843               && cursorX <= endRes)
844       {
845         sr.drawCursor(nextSeq, cursorX, (cursorX - startRes) * charWidth,
846                 offset + ((i - startSeq) * charHeight));
847       }
848     }
849
850     if (av.getSelectionGroup() != null
851             || av.getAlignment().getGroups().size() > 0)
852     {
853       drawGroupsBoundaries(g, startRes, endRes, startSeq, endSeq, offset);
854     }
855
856   }
857
858   void drawGroupsBoundaries(Graphics g1, int startRes, int endRes,
859           int startSeq, int endSeq, int offset)
860   {
861     Graphics2D g = (Graphics2D) g1;
862     //
863     // ///////////////////////////////////
864     // Now outline any areas if necessary
865     // ///////////////////////////////////
866     // SequenceGroup group = av.getSelectionGroup();
867
868     SequenceGroup group = null;
869
870     int sx = -1;
871     int sy = -1;
872     int ex = -1;
873     int groupIndex = -1;
874     int visWidth = (endRes - startRes + 1) * charWidth;
875
876     // if ((group == null) && (av.getAlignment().getGroups().size() > 0))
877     if (av.getAlignment().getGroups().size() > 0)
878     {
879       group = av.getAlignment().getGroups().get(0);
880       groupIndex = 0;
881     }
882
883     if (group != null)
884     {
885       do
886       {
887         int oldY = -1;
888         int i = 0;
889         boolean inGroup = false;
890         int top = -1;
891         int bottom = -1;
892
893         for (i = startSeq; i <= endSeq; i++)
894         {
895           // position of start residue of group relative to startRes, in pixels
896           sx = (group.getStartRes() - startRes) * charWidth;
897           sy = offset + ((i - startSeq) * charHeight);
898           // width of group in pixels
899           ex = (((group.getEndRes() + 1) - group.getStartRes()) * charWidth) - 1;
900
901           if (sx + ex < 0 || sx > visWidth)
902           {
903             continue;
904           }
905
906           if ((sx <= (endRes - startRes) * charWidth)
907                   && group.getSequences(null).contains(
908                           av.getAlignment().getSequenceAt(i)))
909           {
910             if ((bottom == -1)
911                     && !group.getSequences(null).contains(
912                             av.getAlignment().getSequenceAt(i + 1)))
913             {
914               bottom = sy + charHeight;
915             }
916
917             if (!inGroup)
918             {
919               if (((top == -1) && (i == 0))
920                       || !group.getSequences(null).contains(
921                               av.getAlignment().getSequenceAt(i - 1)))
922               {
923                 top = sy;
924               }
925
926               oldY = sy;
927               inGroup = true;
928
929               /*if (group == av.getSelectionGroup())
930               {
931                 g.setStroke(new BasicStroke(1, BasicStroke.CAP_BUTT,
932                         BasicStroke.JOIN_ROUND, 3f, new float[] { 5f, 3f },
933                         0f));
934                 g.setColor(Color.RED);
935               }
936               else
937               {*/
938                 g.setStroke(new BasicStroke());
939                 g.setColor(group.getOutlineColour());
940               // }
941             }
942           }
943           else
944           {
945             if (inGroup)
946             {
947               // if start position is visible, draw vertical line to left of
948               // group
949               if (sx >= 0 && sx < visWidth)
950               {
951                 g.drawLine(sx, oldY, sx, sy);
952               }
953
954               // if end position is visible, draw vertical line to right of
955               // group
956               if (sx + ex < visWidth)
957               {
958                 g.drawLine(sx + ex, oldY, sx + ex, sy);
959               }
960
961               if (sx < 0)
962               {
963                 // ex += sx;
964                 // sx = 0;
965               }
966
967               if (sx + ex > visWidth)
968               {
969                 ex = visWidth;
970               }
971
972               else if (sx + ex >= (endRes - startRes + 1) * charWidth)
973               {
974                 ex = (endRes - startRes + 1) * charWidth;
975               }
976
977               // draw horizontal line at top of group
978               if (top != -1)
979               {
980                 g.drawLine(sx, top, sx + ex, top);
981                 top = -1;
982               }
983
984               // draw horizontal line at bottom of group
985               if (bottom != -1)
986               {
987                 g.drawLine(sx, bottom, sx + ex, bottom);
988                 bottom = -1;
989               }
990
991               inGroup = false;
992             }
993           }
994         }
995
996         if (inGroup)
997         {
998           sy = offset + ((i - startSeq) * charHeight);
999           if (sx >= 0 && sx < visWidth)
1000           {
1001             g.drawLine(sx, oldY, sx, sy);
1002           }
1003
1004           if (sx + ex < visWidth)
1005           {
1006             g.drawLine(sx + ex, oldY, sx + ex, sy);
1007           }
1008
1009           if (sx < 0)
1010           {
1011             ex += sx;
1012             sx = 0;
1013           }
1014
1015           if (sx + ex > visWidth)
1016           {
1017             ex = visWidth;
1018           }
1019           else if (sx + ex >= (endRes - startRes + 1) * charWidth)
1020           {
1021             ex = (endRes - startRes + 1) * charWidth;
1022           }
1023
1024           if (top != -1)
1025           {
1026             g.drawLine(sx, top, sx + ex, top);
1027             top = -1;
1028           }
1029
1030           if (bottom != -1)
1031           {
1032             g.drawLine(sx, bottom - 1, sx + ex, bottom - 1);
1033             bottom = -1;
1034           }
1035
1036           inGroup = false;
1037         }
1038
1039         groupIndex++;
1040
1041         g.setStroke(new BasicStroke());
1042
1043         if (groupIndex >= av.getAlignment().getGroups().size())
1044         {
1045           break;
1046         }
1047
1048         group = av.getAlignment().getGroups().get(groupIndex);
1049
1050       } while (groupIndex < av.getAlignment().getGroups().size());
1051
1052     }
1053
1054   }
1055
1056   /*
1057    * Draw the selection group as a separate image and overlay
1058    */
1059   private BufferedImage drawSelectionGroup()
1060   {
1061     // get a new image of the correct size
1062     BufferedImage selectionImage = setupSelectionImage();
1063
1064     if (selectionImage == null)
1065     {
1066       return null;
1067     }
1068
1069     SequenceGroup group = av.getSelectionGroup();
1070     if (group == null)
1071     {
1072       // nothing to draw
1073       return null;
1074     }
1075
1076     // set up drawing colour
1077     Graphics2D g = (Graphics2D) selectionImage.getGraphics();
1078     // set background to transparent
1079     g.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f));
1080     g.fillRect(0, 0, selectionImage.getWidth(), selectionImage.getHeight());
1081
1082     g.setComposite(AlphaComposite.Src);
1083     g.setStroke(new BasicStroke(1, BasicStroke.CAP_BUTT,
1084             BasicStroke.JOIN_ROUND, 3f, new float[]
1085     { 5f, 3f }, 0f));
1086     g.setColor(Color.RED);
1087
1088     int visWidth = av.getRanges().getViewportWidth() * charWidth;
1089
1090     int startRes = av.getRanges().getStartRes();
1091
1092     // set x start and end positions of group
1093     int startx = (group.getStartRes() - startRes) * charWidth;
1094     int endx = (group.getEndRes() - startRes + 1) * charWidth;
1095
1096     int oldY = -1;
1097     int i = 0;
1098     boolean inGroup = false;
1099     int top = -1;
1100     int bottom = -1;
1101
1102     // get sequences to determine y positions of group
1103     int startSeq = av.getRanges().getStartSeq();
1104     for (i = startSeq; i <= av.getRanges().getEndSeq(); ++i)
1105     {
1106       int sy = (i - startSeq) * charHeight;
1107
1108       if (group.getSequences(null)
1109               .contains(av.getAlignment().getSequenceAt(i)))
1110       {
1111         if ((bottom == -1) && !group.getSequences(null)
1112                 .contains(av.getAlignment().getSequenceAt(i + 1)))
1113         {
1114           bottom = sy + charHeight;
1115         }
1116
1117         if (!inGroup)
1118         {
1119           if (((top == -1) && (i == 0)) || !group.getSequences(null)
1120                   .contains(av.getAlignment().getSequenceAt(i - 1)))
1121           {
1122             top = sy;
1123           }
1124
1125           oldY = sy;
1126           inGroup = true;
1127         }
1128       }
1129       else
1130       {
1131         if (inGroup)
1132         {
1133           // if start position is visible, draw vertical line to left of
1134           // group
1135           if (startx >= 0 && startx < visWidth * charWidth)
1136           {
1137             g.drawLine(startx, oldY, startx, sy);
1138           }
1139
1140           // if end position is visible, draw vertical line to right of
1141           // group
1142           if (endx <= visWidth * charWidth)
1143           {
1144             g.drawLine(endx, oldY, endx, sy);
1145           }
1146
1147           if (endx > visWidth * charWidth)
1148           {
1149             endx = visWidth * charWidth;
1150           }
1151
1152           // draw horizontal line at top of group
1153           if (top != -1)
1154           {
1155             g.drawLine(startx, top, endx, top);
1156             top = -1;
1157           }
1158
1159           // draw horizontal line at bottom of group
1160           if (bottom != -1)
1161           {
1162             g.drawLine(startx, bottom, endx, bottom);
1163             bottom = -1;
1164           }
1165
1166           inGroup = false;
1167         }
1168       }
1169     }
1170     if (inGroup)
1171     {
1172       int sy = (i - startSeq) * charHeight;
1173       if (startx >= 0 && startx < visWidth)
1174       {
1175         g.drawLine(startx, oldY, startx, sy);
1176       }
1177
1178       if (endx < visWidth)
1179       {
1180         g.drawLine(endx, oldY, endx, sy);
1181       }
1182
1183       if (endx > visWidth)
1184       {
1185         endx = visWidth;
1186       }
1187
1188       if (top != -1)
1189       {
1190         g.drawLine(startx, top, endx, top);
1191         top = -1;
1192       }
1193
1194       if (bottom != -1)
1195       {
1196         g.drawLine(startx, bottom - 1, endx, bottom - 1);
1197         bottom = -1;
1198       }
1199
1200       inGroup = false;
1201     }
1202
1203     return selectionImage;
1204   }
1205
1206   /**
1207    * DOCUMENT ME!
1208    * 
1209    * @param results
1210    *          DOCUMENT ME!
1211    */
1212   public void highlightSearchResults(SearchResultsI results)
1213   {
1214     img = null;
1215
1216     av.setSearchResults(results);
1217
1218     repaint();
1219   }
1220
1221   @Override
1222   public void propertyChange(PropertyChangeEvent evt)
1223   {
1224     String eventName = evt.getPropertyName();
1225
1226     if (av.getWrapAlignment())
1227     {
1228       if (eventName.equals(ViewportRanges.STARTRES))
1229       {
1230         repaint();
1231       }
1232     }
1233     else
1234     {
1235       int scrollX = 0;
1236       if (eventName.equals(ViewportRanges.STARTRES))
1237       {
1238         // Make sure we're not trying to draw a panel
1239         // larger than the visible window
1240         ViewportRanges vpRanges = av.getRanges();
1241         scrollX = (int) evt.getNewValue() - (int) evt.getOldValue();
1242         int range = vpRanges.getEndRes() - vpRanges.getStartRes();
1243         if (scrollX > range)
1244         {
1245           scrollX = range;
1246         }
1247         else if (scrollX < -range)
1248         {
1249           scrollX = -range;
1250         }
1251       }
1252
1253       // Both scrolling and resizing change viewport ranges: scrolling changes
1254       // both start and end points, but resize only changes end values.
1255       // Here we only want to fastpaint on a scroll, with resize using a normal
1256       // paint, so scroll events are identified as changes to the horizontal or
1257       // vertical start value.
1258       if (eventName.equals(ViewportRanges.STARTRES))
1259       {
1260         // scroll - startres and endres both change
1261         fastPaint(scrollX, 0);
1262       }
1263       else if (eventName.equals(ViewportRanges.STARTSEQ))
1264       {
1265         // scroll
1266         fastPaint(0, (int) evt.getNewValue() - (int) evt.getOldValue());
1267       }
1268     }
1269   }
1270 }