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