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