b6153a85599da38bfe0a13549500bc44b14864bb
[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   /*
447    * Set up a buffered image of the correct height and size for the sequence canvas
448    */
449   private BufferedImage setupImage()
450   {
451     BufferedImage lcimg = null;
452
453     int width = getWidth();
454     int height = getHeight();
455
456     width -= (width % charWidth);
457     height -= (height % charHeight);
458
459     if ((width < 1) || (height < 1))
460     {
461       return null;
462     }
463
464     try
465     {
466       lcimg = new BufferedImage(width, height,
467               BufferedImage.TYPE_INT_ARGB); // ARGB so alpha compositing works
468     } catch (OutOfMemoryError er)
469     {
470       System.gc();
471       System.err.println(
472               "Group image OutOfMemory Redraw Error.\n" + er);
473       new OOMWarning("Creating alignment image for display", er);
474
475       return null;
476     }
477
478     return lcimg;
479   }
480
481   /**
482    * DOCUMENT ME!
483    * 
484    * @param cwidth
485    *          DOCUMENT ME!
486    * 
487    * @return DOCUMENT ME!
488    */
489   public int getWrappedCanvasWidth(int cwidth)
490   {
491     FontMetrics fm = getFontMetrics(av.getFont());
492
493     LABEL_EAST = 0;
494     LABEL_WEST = 0;
495
496     if (av.getScaleRightWrapped())
497     {
498       LABEL_EAST = fm.stringWidth(getMask());
499     }
500
501     if (av.getScaleLeftWrapped())
502     {
503       LABEL_WEST = fm.stringWidth(getMask());
504     }
505
506     return (cwidth - LABEL_EAST - LABEL_WEST) / charWidth;
507   }
508
509   /**
510    * Generates a string of zeroes.
511    * 
512    * @return String
513    */
514   String getMask()
515   {
516     String mask = "00";
517     int maxWidth = 0;
518     int tmp;
519     for (int i = 0; i < av.getAlignment().getHeight(); i++)
520     {
521       tmp = av.getAlignment().getSequenceAt(i).getEnd();
522       if (tmp > maxWidth)
523       {
524         maxWidth = tmp;
525       }
526     }
527
528     for (int i = maxWidth; i > 0; i /= 10)
529     {
530       mask += "0";
531     }
532     return mask;
533   }
534
535   /**
536    * DOCUMENT ME!
537    * 
538    * @param g
539    *          DOCUMENT ME!
540    * @param canvasWidth
541    *          DOCUMENT ME!
542    * @param canvasHeight
543    *          DOCUMENT ME!
544    * @param startRes
545    *          DOCUMENT ME!
546    */
547   public void drawWrappedPanel(Graphics g, int canvasWidth,
548           int canvasHeight, int startRes)
549   {
550     updateViewport();
551     AlignmentI al = av.getAlignment();
552
553     FontMetrics fm = getFontMetrics(av.getFont());
554
555     LABEL_EAST = 0;
556     LABEL_WEST = 0;
557
558     if (av.getScaleRightWrapped())
559     {
560       LABEL_EAST = fm.stringWidth(getMask());
561     }
562
563     if (av.getScaleLeftWrapped())
564     {
565       LABEL_WEST = fm.stringWidth(getMask());
566     }
567
568     int hgap = charHeight;
569     if (av.getScaleAboveWrapped())
570     {
571       hgap += charHeight;
572     }
573
574     int cWidth = (canvasWidth - LABEL_EAST - LABEL_WEST) / charWidth;
575     int cHeight = av.getAlignment().getHeight() * charHeight;
576
577     av.setWrappedWidth(cWidth);
578
579     av.getRanges().setViewportStartAndWidth(startRes, cWidth);
580
581     int endx;
582     int ypos = hgap;
583     int maxwidth = av.getAlignment().getWidth();
584
585     if (av.hasHiddenColumns())
586     {
587       maxwidth = av.getAlignment().getHiddenColumns()
588               .findColumnPosition(maxwidth);
589     }
590
591     while ((ypos <= canvasHeight) && (startRes < maxwidth))
592     {
593       endx = startRes + cWidth - 1;
594
595       if (endx > maxwidth)
596       {
597         endx = maxwidth;
598       }
599
600       g.setFont(av.getFont());
601       g.setColor(Color.black);
602
603       if (av.getScaleLeftWrapped())
604       {
605         drawWestScale(g, startRes, endx, ypos);
606       }
607
608       if (av.getScaleRightWrapped())
609       {
610         g.translate(canvasWidth - LABEL_EAST, 0);
611         drawEastScale(g, startRes, endx, ypos);
612         g.translate(-(canvasWidth - LABEL_EAST), 0);
613       }
614
615       g.translate(LABEL_WEST, 0);
616
617       if (av.getScaleAboveWrapped())
618       {
619         drawNorthScale(g, startRes, endx, ypos);
620       }
621
622       if (av.hasHiddenColumns() && av.getShowHiddenMarkers())
623       {
624         g.setColor(Color.blue);
625         int res;
626         HiddenColumns hidden = av.getAlignment().getHiddenColumns();
627         List<Integer> positions = hidden.findHiddenRegionPositions();
628         for (int pos : positions)
629         {
630           res = pos - startRes;
631
632           if (res < 0 || res > endx - startRes)
633           {
634             continue;
635           }
636
637           gg.fillPolygon(
638                   new int[] { res * charWidth - charHeight / 4,
639                       res * charWidth + charHeight / 4, res * charWidth },
640                   new int[] { ypos - (charHeight / 2),
641                       ypos - (charHeight / 2), ypos - (charHeight / 2) + 8 },
642                   3);
643
644         }
645       }
646
647       // When printing we have an extra clipped region,
648       // the Printable page which we need to account for here
649       Shape clip = g.getClip();
650
651       if (clip == null)
652       {
653         g.setClip(0, 0, cWidth * charWidth, canvasHeight);
654       }
655       else
656       {
657         g.setClip(0, (int) clip.getBounds().getY(), cWidth * charWidth,
658                 (int) clip.getBounds().getHeight());
659       }
660
661       drawPanel(g, startRes, endx, 0, al.getHeight() - 1, ypos);
662
663       if (av.isShowAnnotation())
664       {
665         g.translate(0, cHeight + ypos + 3);
666         if (annotations == null)
667         {
668           annotations = new AnnotationPanel(av);
669         }
670
671         annotations.renderer.drawComponent(annotations, av, g, -1,
672                 startRes, endx + 1);
673         g.translate(0, -cHeight - ypos - 3);
674       }
675       g.setClip(clip);
676       g.translate(-LABEL_WEST, 0);
677
678       ypos += cHeight + getAnnotationHeight() + hgap;
679
680       startRes += cWidth;
681     }
682   }
683
684   /*
685    * Draw a selection group over a wrapped alignment
686    */
687   private void drawWrappedSelection(Graphics2D g, SequenceGroup group,
688           int canvasWidth,
689           int canvasHeight, int startRes)
690   {
691     // height gap above each panel
692     int hgap = charHeight;
693     if (av.getScaleAboveWrapped())
694     {
695       hgap += charHeight;
696     }
697
698     int cWidth = (canvasWidth - LABEL_EAST - LABEL_WEST) / charWidth;
699     int cHeight = av.getAlignment().getHeight() * charHeight;
700
701     int startx = startRes;
702     int endx;
703     int ypos = hgap; // vertical offset
704     int maxwidth = av.getAlignment().getWidth();
705
706     if (av.hasHiddenColumns())
707     {
708       maxwidth = av.getAlignment().getHiddenColumns()
709               .findColumnPosition(maxwidth);
710     }
711
712     // chop the wrapped alignment extent up into panel-sized blocks and treat
713     // each block as if it were a block from an unwrapped alignment
714     while ((ypos <= canvasHeight) && (startx < maxwidth))
715     {
716       // set end value to be start + width, or maxwidth, whichever is smaller
717       endx = startx + cWidth - 1;
718
719       if (endx > maxwidth)
720       {
721         endx = maxwidth;
722       }
723
724       g.translate(LABEL_WEST, 0);
725
726       drawUnwrappedSelection(g, group, startx, endx, 0,
727               av.getAlignment().getHeight() - 1,
728               ypos);
729
730       g.translate(-LABEL_WEST, 0);
731
732       // update vertical offset
733       ypos += cHeight + getAnnotationHeight() + hgap;
734
735       // update horizontal offset
736       startx += cWidth;
737     }
738   }
739
740   int getAnnotationHeight()
741   {
742     if (!av.isShowAnnotation())
743     {
744       return 0;
745     }
746
747     if (annotations == null)
748     {
749       annotations = new AnnotationPanel(av);
750     }
751
752     return annotations.adjustPanelHeight();
753   }
754
755   /**
756    * DOCUMENT ME!
757    * 
758    * @param g1
759    *          DOCUMENT ME!
760    * @param startRes
761    *          DOCUMENT ME!
762    * @param endRes
763    *          DOCUMENT ME!
764    * @param startSeq
765    *          DOCUMENT ME!
766    * @param endSeq
767    *          DOCUMENT ME!
768    * @param offset
769    *          DOCUMENT ME!
770    */
771   public void drawPanel(Graphics g1, int startRes, int endRes,
772           int startSeq, int endSeq, int offset)
773   {
774     updateViewport();
775     if (!av.hasHiddenColumns())
776     {
777       draw(g1, startRes, endRes, startSeq, endSeq, offset);
778     }
779     else
780     {
781       int screenY = 0;
782       int blockStart = startRes;
783       int blockEnd = endRes;
784
785       for (int[] region : av.getAlignment().getHiddenColumns()
786               .getHiddenColumnsCopy())
787       {
788         int hideStart = region[0];
789         int hideEnd = region[1];
790
791         if (hideStart <= blockStart)
792         {
793           blockStart += (hideEnd - hideStart) + 1;
794           continue;
795         }
796
797         blockEnd = hideStart - 1;
798
799         g1.translate(screenY * charWidth, 0);
800
801         draw(g1, blockStart, blockEnd, startSeq, endSeq, offset);
802
803         if (av.getShowHiddenMarkers())
804         {
805           g1.setColor(Color.blue);
806
807           g1.drawLine((blockEnd - blockStart + 1) * charWidth - 1,
808                   0 + offset, (blockEnd - blockStart + 1) * charWidth - 1,
809                   (endSeq - startSeq + 1) * charHeight + offset);
810         }
811
812         g1.translate(-screenY * charWidth, 0);
813         screenY += blockEnd - blockStart + 1;
814         blockStart = hideEnd + 1;
815
816         if (screenY > (endRes - startRes))
817         {
818           // already rendered last block
819           return;
820         }
821       }
822
823       if (screenY <= (endRes - startRes))
824       {
825         // remaining visible region to render
826         blockEnd = blockStart + (endRes - startRes) - screenY;
827         g1.translate(screenY * charWidth, 0);
828         draw(g1, blockStart, blockEnd, startSeq, endSeq, offset);
829
830         g1.translate(-screenY * charWidth, 0);
831       }
832     }
833
834   }
835
836   private void draw(Graphics g, int startRes, int endRes, int startSeq,
837           int endSeq, int offset)
838   {
839     g.setFont(av.getFont());
840     seqRdr.prepare(g, av.isRenderGaps());
841
842     SequenceI nextSeq;
843
844     // / First draw the sequences
845     // ///////////////////////////
846     for (int i = startSeq; i <= endSeq; i++)
847     {
848       nextSeq = av.getAlignment().getSequenceAt(i);
849       if (nextSeq == null)
850       {
851         // occasionally, a race condition occurs such that the alignment row is
852         // empty
853         continue;
854       }
855       seqRdr.drawSequence(nextSeq, av.getAlignment().findAllGroups(nextSeq),
856               startRes, endRes, offset + ((i - startSeq) * charHeight));
857
858       if (av.isShowSequenceFeatures())
859       {
860         fr.drawSequence(g, nextSeq, startRes, endRes, offset
861                 + ((i - startSeq) * charHeight), false);
862       }
863
864       // / Highlight search Results once all sequences have been drawn
865       // ////////////////////////////////////////////////////////
866       if (av.hasSearchResults())
867       {
868         int[] visibleResults = av.getSearchResults().getResults(nextSeq,
869                 startRes, endRes);
870         if (visibleResults != null)
871         {
872           for (int r = 0; r < visibleResults.length; r += 2)
873           {
874             seqRdr.drawHighlightedText(nextSeq, visibleResults[r],
875                     visibleResults[r + 1], (visibleResults[r] - startRes)
876                             * charWidth, offset
877                             + ((i - startSeq) * charHeight));
878           }
879         }
880       }
881
882       if (av.cursorMode && cursorY == i && cursorX >= startRes
883               && cursorX <= endRes)
884       {
885         seqRdr.drawCursor(nextSeq, cursorX, (cursorX - startRes) * charWidth,
886                 offset + ((i - startSeq) * charHeight));
887       }
888     }
889
890     if (av.getSelectionGroup() != null
891             || av.getAlignment().getGroups().size() > 0)
892     {
893       drawGroupsBoundaries(g, startRes, endRes, startSeq, endSeq, offset);
894     }
895
896   }
897
898   void drawGroupsBoundaries(Graphics g1, int startRes, int endRes,
899           int startSeq, int endSeq, int offset)
900   {
901     Graphics2D g = (Graphics2D) g1;
902     //
903     // ///////////////////////////////////
904     // Now outline any areas if necessary
905     // ///////////////////////////////////
906
907     SequenceGroup group = null;
908     int groupIndex = -1;
909
910     if (av.getAlignment().getGroups().size() > 0)
911     {
912       group = av.getAlignment().getGroups().get(0);
913       groupIndex = 0;
914     }
915
916     if (group != null)
917     {
918       g.setStroke(new BasicStroke());
919       g.setColor(group.getOutlineColour());
920       
921       do
922       {
923         drawPartialGroupOutline(g, group, startRes, endRes, startSeq,
924                 endSeq, offset);
925         
926         groupIndex++;
927
928         g.setStroke(new BasicStroke());
929
930         if (groupIndex >= av.getAlignment().getGroups().size())
931         {
932           break;
933         }
934
935         group = av.getAlignment().getGroups().get(groupIndex);
936
937       } while (groupIndex < av.getAlignment().getGroups().size());
938
939     }
940
941   }
942
943
944   /*
945    * Draw the selection group as a separate image and overlay
946    */
947   private BufferedImage drawSelectionGroup(int startRes, int endRes,
948           int startSeq, int endSeq)
949   {
950     // get a new image of the correct size
951     BufferedImage selectionImage = setupImage();
952
953     if (selectionImage == null)
954     {
955       return null;
956     }
957
958     SequenceGroup group = av.getSelectionGroup();
959     if (group == null)
960     {
961       // nothing to draw
962       return null;
963     }
964
965     // set up drawing colour
966     Graphics2D g = (Graphics2D) selectionImage.getGraphics();
967
968     // set background to transparent
969     g.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f));
970     g.fillRect(0, 0, selectionImage.getWidth(), selectionImage.getHeight());
971
972     // set up foreground to draw red dashed line
973     g.setComposite(AlphaComposite.Src);
974     g.setStroke(new BasicStroke(1, BasicStroke.CAP_BUTT,
975             BasicStroke.JOIN_ROUND, 3f, new float[]
976     { 5f, 3f }, 0f));
977     g.setColor(Color.RED);
978
979     if (!av.getWrapAlignment())
980     {
981       drawUnwrappedSelection(g, group, startRes, endRes, startSeq, endSeq,
982               0);
983     }
984     else
985     {
986       drawWrappedSelection(g, group, getWidth(), getHeight(),
987               av.getRanges().getStartRes());
988     }
989
990     g.dispose();
991     return selectionImage;
992   }
993
994   /*
995    * Draw a selection group over an unwrapped alignment
996    * @param g graphics object to draw with
997    * @param group selection group
998    * @param startRes start residue of area to draw
999    * @param endRes end residue of area to draw
1000    * @param startSeq start sequence of area to draw
1001    * @param endSeq end sequence of area to draw
1002    * @param offset vertical offset (used when called from wrapped alignment code)
1003    */
1004   private void drawUnwrappedSelection(Graphics2D g, SequenceGroup group,
1005           int startRes, int endRes, int startSeq, int endSeq, int offset)
1006   {
1007     if (!av.hasHiddenColumns())
1008     {
1009       drawPartialGroupOutline(g, group, startRes, endRes, startSeq, endSeq,
1010               offset);
1011     }
1012     else
1013     {
1014       // package into blocks of visible columns
1015       int screenY = 0;
1016       int blockStart = startRes;
1017       int blockEnd = endRes;
1018
1019       for (int[] region : av.getAlignment().getHiddenColumns()
1020               .getHiddenColumnsCopy())
1021       {
1022         int hideStart = region[0];
1023         int hideEnd = region[1];
1024
1025         if (hideStart <= blockStart)
1026         {
1027           blockStart += (hideEnd - hideStart) + 1;
1028           continue;
1029         }
1030
1031         blockEnd = hideStart - 1;
1032
1033         g.translate(screenY * charWidth, 0);
1034         drawPartialGroupOutline(g, group,
1035                 blockStart, blockEnd, startSeq, endSeq, offset);
1036
1037         g.translate(-screenY * charWidth, 0);
1038         screenY += blockEnd - blockStart + 1;
1039         blockStart = hideEnd + 1;
1040
1041         if (screenY > (endRes - startRes))
1042         {
1043           // already rendered last block
1044           break;
1045         }
1046       }
1047
1048       if (screenY <= (endRes - startRes))
1049       {
1050         // remaining visible region to render
1051         blockEnd = blockStart + (endRes - startRes) - screenY;
1052         g.translate(screenY * charWidth, 0);
1053         drawPartialGroupOutline(g, group,
1054                 blockStart, blockEnd, startSeq, endSeq, offset);
1055         
1056         g.translate(-screenY * charWidth, 0);
1057       }
1058     }
1059   }
1060
1061   /*
1062    * Draw the selection group as a separate image and overlay
1063    */
1064   private void drawPartialGroupOutline(Graphics2D g, SequenceGroup group,
1065           int startRes, int endRes, int startSeq, int endSeq,
1066           int verticalOffset)
1067   {
1068     int visWidth = (endRes - startRes + 1) * charWidth;
1069
1070     int oldY = -1;
1071     int i = 0;
1072     boolean inGroup = false;
1073     int top = -1;
1074     int bottom = -1;
1075
1076     int sx = -1;
1077     int sy = -1;
1078     int xwidth = -1;
1079
1080     for (i = startSeq; i <= endSeq; i++)
1081     {
1082       // position of start residue of group relative to startRes, in pixels
1083       sx = (group.getStartRes() - startRes) * charWidth;
1084
1085       // width of group in pixels
1086       xwidth = (((group.getEndRes() + 1) - group.getStartRes()) * charWidth)
1087               - 1;
1088
1089       sy = verticalOffset + (i - startSeq) * charHeight;
1090
1091       if (sx + xwidth < 0 || sx > visWidth)
1092       {
1093         continue;
1094       }
1095
1096       if ((sx <= (endRes - startRes) * charWidth)
1097               && group.getSequences(null)
1098                       .contains(av.getAlignment().getSequenceAt(i)))
1099       {
1100         if ((bottom == -1) && !group.getSequences(null)
1101                 .contains(av.getAlignment().getSequenceAt(i + 1)))
1102         {
1103           bottom = sy + charHeight;
1104         }
1105
1106         if (!inGroup)
1107         {
1108           if (((top == -1) && (i == 0)) || !group.getSequences(null)
1109                   .contains(av.getAlignment().getSequenceAt(i - 1)))
1110           {
1111             top = sy;
1112           }
1113
1114           oldY = sy;
1115           inGroup = true;
1116         }
1117       }
1118       else
1119       {
1120         if (inGroup)
1121         {
1122           // if start position is visible, draw vertical line to left of
1123           // group
1124           if (sx >= 0 && sx < visWidth)
1125           {
1126             g.drawLine(sx, oldY, sx, sy);
1127           }
1128
1129           // if end position is visible, draw vertical line to right of
1130           // group
1131           if (sx + xwidth < visWidth)
1132           {
1133             g.drawLine(sx + xwidth, oldY, sx + xwidth, sy);
1134           }
1135
1136           if (sx < 0)
1137           {
1138             xwidth += sx;
1139             sx = 0;
1140           }
1141
1142           // don't let width extend beyond current block, or group extent
1143           // fixes JAL-2672
1144           if (sx + xwidth >= (endRes - startRes + 1) * charWidth)
1145           {
1146             xwidth = (endRes - startRes + 1) * charWidth - sx;
1147           }
1148           
1149           // draw horizontal line at top of group
1150           if (top != -1)
1151           {
1152             g.drawLine(sx, top, sx + xwidth, top);
1153             top = -1;
1154           }
1155
1156           // draw horizontal line at bottom of group
1157           if (bottom != -1)
1158           {
1159             g.drawLine(sx, bottom, sx + xwidth, bottom);
1160             bottom = -1;
1161           }
1162
1163           inGroup = false;
1164         }
1165       }
1166     }
1167
1168     if (inGroup)
1169     {
1170       sy = verticalOffset + ((i - startSeq) * charHeight);
1171       if (sx >= 0 && sx < visWidth)
1172       {
1173         g.drawLine(sx, oldY, sx, sy);
1174       }
1175
1176       if (sx + xwidth < visWidth)
1177       {
1178         g.drawLine(sx + xwidth, oldY, sx + xwidth, sy);
1179       }
1180
1181       if (sx < 0)
1182       {
1183         xwidth += sx;
1184         sx = 0;
1185       }
1186
1187       if (sx + xwidth > visWidth)
1188       {
1189         xwidth = visWidth;
1190       }
1191       else if (sx + xwidth >= (endRes - startRes + 1) * charWidth)
1192       {
1193         xwidth = (endRes - startRes + 1) * charWidth;
1194       }
1195
1196       if (top != -1)
1197       {
1198         g.drawLine(sx, top, sx + xwidth, top);
1199         top = -1;
1200       }
1201
1202       if (bottom != -1)
1203       {
1204         g.drawLine(sx, bottom - 1, sx + xwidth, bottom - 1);
1205         bottom = -1;
1206       }
1207
1208       inGroup = false;
1209     }
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       fastPaint = true;
1235       repaint();
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 }