JAL-2609 tidy label width code, some checkstyle warnings
[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.util.Comparison;
31 import jalview.viewmodel.ViewportListenerI;
32 import jalview.viewmodel.ViewportRanges;
33
34 import java.awt.AlphaComposite;
35 import java.awt.BasicStroke;
36 import java.awt.BorderLayout;
37 import java.awt.Color;
38 import java.awt.FontMetrics;
39 import java.awt.Graphics;
40 import java.awt.Graphics2D;
41 import java.awt.RenderingHints;
42 import java.awt.Shape;
43 import java.awt.image.BufferedImage;
44 import java.beans.PropertyChangeEvent;
45 import java.util.List;
46
47 import javax.swing.JComponent;
48
49 /**
50  * The Swing component on which the alignment sequences, and annotations (if
51  * shown), are drawn. This includes scales above, left and right (if shown) in
52  * Wrapped mode, but not the scale above in Unwrapped mode.
53  * 
54  */
55 public class SeqCanvas extends JComponent implements ViewportListenerI
56 {
57   private static final String ZEROS = "0000000000";
58
59   final FeatureRenderer fr;
60
61   BufferedImage img;
62
63   AlignViewport av;
64
65   int cursorX = 0;
66
67   int cursorY = 0;
68
69   private final SequenceRenderer seqRdr;
70
71   private boolean fastPaint = false;
72
73   private boolean fastpainting = false;
74
75   private AnnotationPanel annotations;
76
77   /*
78    * measurements for drawing a wrapped alignment
79    */
80   private int labelWidthEast; // label right width in pixels if shown
81
82   private int labelWidthWest; // label left width in pixels if shown
83
84   private int wrappedSpaceAboveAlignment; // gap between widths
85
86   private int wrappedRepeatHeightPx; // height in pixels of wrapped width
87
88   private int wrappedVisibleWidths; // number of wrapped widths displayed
89
90   private Graphics2D gg;
91
92   /**
93    * Creates a new SeqCanvas object.
94    * 
95    * @param ap
96    */
97   public SeqCanvas(AlignmentPanel ap)
98   {
99     this.av = ap.av;
100     fr = new FeatureRenderer(ap);
101     seqRdr = new SequenceRenderer(av);
102     setLayout(new BorderLayout());
103     PaintRefresher.Register(this, av.getSequenceSetId());
104     setBackground(Color.white);
105
106     av.getRanges().addPropertyChangeListener(this);
107   }
108
109   public SequenceRenderer getSequenceRenderer()
110   {
111     return seqRdr;
112   }
113
114   public FeatureRenderer getFeatureRenderer()
115   {
116     return fr;
117   }
118
119   /**
120    * Draws the scale above a region of a wrapped alignment, consisting of a
121    * column number every major interval (10 columns).
122    * 
123    * @param g
124    *          the graphics context to draw on, positioned at the start (bottom
125    *          left) of the line on which to draw any scale marks
126    * @param startx
127    *          start alignment column (0..)
128    * @param endx
129    *          end alignment column (0..)
130    * @param ypos
131    *          y offset to draw at
132    */
133   private void drawNorthScale(Graphics g, int startx, int endx, int ypos)
134   {
135     int charHeight = av.getCharHeight();
136     int charWidth = av.getCharWidth();
137
138     /*
139      * white fill the scale space (for the fastPaint case)
140      */
141     g.setColor(Color.white);
142     g.fillRect(0, ypos - charHeight - charHeight / 2, getWidth(),
143             charHeight * 3 / 2 + 2);
144     g.setColor(Color.black);
145
146     List<ScaleMark> marks = new ScaleRenderer().calculateMarks(av, startx,
147             endx);
148     for (ScaleMark mark : marks)
149     {
150       int mpos = mark.column; // (i - startx - 1)
151       if (mpos < 0)
152       {
153         continue;
154       }
155       String mstring = mark.text;
156
157       if (mark.major)
158       {
159         if (mstring != null)
160         {
161           g.drawString(mstring, mpos * charWidth, ypos - (charHeight / 2));
162         }
163
164         /*
165          * draw a tick mark below the column number, centred on the column;
166          * height of tick mark is 4 pixels less than half a character
167          */
168         int xpos = (mpos * charWidth) + (charWidth / 2);
169         g.drawLine(xpos, (ypos + 2) - (charHeight / 2), xpos, ypos - 2);
170       }
171     }
172   }
173
174   /**
175    * Draw the scale to the left or right of a wrapped alignment
176    * 
177    * @param g
178    *          graphics context, positioned at the start of the scale to be drawn
179    * @param startx
180    *          first column of wrapped width (0.. excluding any hidden columns)
181    * @param endx
182    *          last column of wrapped width (0.. excluding any hidden columns)
183    * @param ypos
184    *          vertical offset at which to begin the scale
185    * @param left
186    *          if true, scale is left of residues, if false, scale is right
187    */
188   void drawVerticalScale(Graphics g, final int startx, final int endx,
189           final int ypos, final boolean left)
190   {
191     int charHeight = av.getCharHeight();
192     int charWidth = av.getCharWidth();
193
194     int yPos = ypos + charHeight;
195     int startX = startx;
196     int endX = endx;
197
198     if (av.hasHiddenColumns())
199     {
200       HiddenColumns hiddenColumns = av.getAlignment().getHiddenColumns();
201       startX = hiddenColumns.adjustForHiddenColumns(startx);
202       endX = hiddenColumns.adjustForHiddenColumns(endx);
203     }
204     FontMetrics fm = getFontMetrics(av.getFont());
205
206     for (int i = 0; i < av.getAlignment().getHeight(); i++)
207     {
208       SequenceI seq = av.getAlignment().getSequenceAt(i);
209
210       /*
211        * find sequence position of first non-gapped position -
212        * to the right if scale left, to the left if scale right
213        */
214       int index = left ? startX : endX;
215       int value = -1;
216       while (index >= startX && index <= endX)
217       {
218         if (!Comparison.isGap(seq.getCharAt(index)))
219         {
220           value = seq.findPosition(index);
221           break;
222         }
223         if (left)
224         {
225           index++;
226         }
227         else
228         {
229           index--;
230         }
231       }
232
233       /*
234        * white fill the space for the scale
235        */
236       g.setColor(Color.white);
237       int y = (yPos + (i * charHeight)) - (charHeight / 5);
238       // fillRect origin is top left of rectangle
239       g.fillRect(0, y - charHeight, left ? labelWidthWest : labelWidthEast,
240               charHeight + 1);
241
242       if (value != -1)
243       {
244         /*
245          * draw scale value, right justified within its width less half a
246          * character width padding on the right
247          */
248         int labelSpace = left ? labelWidthWest : labelWidthEast;
249         labelSpace -= charWidth / 2; // leave space to the right
250         String valueAsString = String.valueOf(value);
251         int labelLength = fm.stringWidth(valueAsString);
252         int xOffset = labelSpace - labelLength;
253         g.setColor(Color.black);
254         g.drawString(valueAsString, xOffset, y);
255       }
256     }
257   }
258
259   /**
260    * Does a fast paint of an alignment in response to a scroll. Most of the
261    * visible region is simply copied and shifted, and then any newly visible
262    * columns or rows are drawn. The scroll may be horizontal or vertical, but
263    * not both at once. Scrolling may be the result of
264    * <ul>
265    * <li>dragging a scroll bar</li>
266    * <li>clicking in the scroll bar</li>
267    * <li>scrolling by trackpad, middle mouse button, or other device</li>
268    * <li>by moving the box in the Overview window</li>
269    * <li>programmatically to make a highlighted position visible</li>
270    * </ul>
271    * 
272    * @param horizontal
273    *          columns to shift right (positive) or left (negative)
274    * @param vertical
275    *          rows to shift down (positive) or up (negative)
276    */
277   public void fastPaint(int horizontal, int vertical)
278   {
279     if (fastpainting || gg == null || img == null)
280     {
281       return;
282     }
283     fastpainting = true;
284     fastPaint = true;
285
286     try
287     {
288       int charHeight = av.getCharHeight();
289       int charWidth = av.getCharWidth();
290     
291       ViewportRanges ranges = av.getRanges();
292       int startRes = ranges.getStartRes();
293       int endRes = ranges.getEndRes();
294       int startSeq = ranges.getStartSeq();
295       int endSeq = ranges.getEndSeq();
296       int transX = 0;
297       int transY = 0;
298
299     gg.copyArea(horizontal * charWidth, vertical * charHeight,
300             img.getWidth(), img.getHeight(), -horizontal * charWidth,
301             -vertical * charHeight);
302
303     if (horizontal > 0) // scrollbar pulled right, image to the left
304     {
305       transX = (endRes - startRes - horizontal) * charWidth;
306       startRes = endRes - horizontal;
307     }
308     else if (horizontal < 0)
309     {
310       endRes = startRes - horizontal;
311     }
312     else if (vertical > 0) // scroll down
313     {
314       startSeq = endSeq - vertical;
315
316       if (startSeq < ranges.getStartSeq())
317       { // ie scrolling too fast, more than a page at a time
318         startSeq = ranges.getStartSeq();
319       }
320       else
321       {
322         transY = img.getHeight() - ((vertical + 1) * charHeight);
323       }
324     }
325     else if (vertical < 0)
326     {
327       endSeq = startSeq - vertical;
328
329       if (endSeq > ranges.getEndSeq())
330       {
331         endSeq = ranges.getEndSeq();
332       }
333     }
334
335     gg.translate(transX, transY);
336     drawPanel(gg, startRes, endRes, startSeq, endSeq, 0);
337     gg.translate(-transX, -transY);
338
339     repaint();
340     } finally
341     {
342       fastpainting = false;
343     }
344   }
345
346   @Override
347   public void paintComponent(Graphics g)
348   {
349     super.paintComponent(g);    
350     
351     int charHeight = av.getCharHeight();
352     int charWidth = av.getCharWidth();
353
354     ViewportRanges ranges = av.getRanges();
355
356     int width = getWidth();
357     int height = getHeight();
358
359     width -= (width % charWidth);
360     height -= (height % charHeight);
361
362     // selectImage is the selection group outline image
363     BufferedImage selectImage = drawSelectionGroup(
364             ranges.getStartRes(), ranges.getEndRes(),
365             ranges.getStartSeq(), ranges.getEndSeq());
366
367     if ((img != null) && (fastPaint
368             || (getVisibleRect().width != g.getClipBounds().width)
369             || (getVisibleRect().height != g.getClipBounds().height)))
370     {
371       BufferedImage lcimg = buildLocalImage(selectImage);
372       g.drawImage(lcimg, 0, 0, this);
373       fastPaint = false;
374     }
375     else if ((width > 0) && (height > 0))
376     {
377       // img is a cached version of the last view we drew, if any
378       // if we have no img or the size has changed, make a new one
379       if (img == null || width != img.getWidth()
380               || height != img.getHeight())
381       {
382         img = setupImage();
383         if (img == null)
384         {
385           return;
386         }
387         gg = (Graphics2D) img.getGraphics();
388         gg.setFont(av.getFont());
389       }
390
391       if (av.antiAlias)
392       {
393         gg.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
394                 RenderingHints.VALUE_ANTIALIAS_ON);
395       }
396
397       gg.setColor(Color.white);
398       gg.fillRect(0, 0, img.getWidth(), img.getHeight());
399
400       if (av.getWrapAlignment())
401       {
402         drawWrappedPanel(gg, getWidth(), getHeight(), ranges.getStartRes());
403       }
404       else
405       {
406         drawPanel(gg, ranges.getStartRes(), ranges.getEndRes(),
407                 ranges.getStartSeq(), ranges.getEndSeq(), 0);
408       }
409
410       // lcimg is a local *copy* of img which we'll draw selectImage on top of
411       BufferedImage lcimg = buildLocalImage(selectImage);
412       g.drawImage(lcimg, 0, 0, this);
413     }
414   }
415   
416   /**
417    * Draw an alignment panel for printing
418    * 
419    * @param g1
420    *          Graphics object to draw with
421    * @param startRes
422    *          start residue of print area
423    * @param endRes
424    *          end residue of print area
425    * @param startSeq
426    *          start sequence of print area
427    * @param endSeq
428    *          end sequence of print area
429    */
430   public void drawPanelForPrinting(Graphics g1, int startRes, int endRes,
431           int startSeq, int endSeq)
432   {
433     drawPanel(g1, startRes, endRes, startSeq, endSeq, 0);
434
435     BufferedImage selectImage = drawSelectionGroup(startRes, endRes,
436             startSeq, endSeq);
437     if (selectImage != null)
438     {
439       ((Graphics2D) g1).setComposite(AlphaComposite
440               .getInstance(AlphaComposite.SRC_OVER));
441       g1.drawImage(selectImage, 0, 0, this);
442     }
443   }
444
445   /**
446    * Draw a wrapped alignment panel for printing
447    * 
448    * @param g
449    *          Graphics object to draw with
450    * @param canvasWidth
451    *          width of drawing area
452    * @param canvasHeight
453    *          height of drawing area
454    * @param startRes
455    *          start residue of print area
456    */
457   public void drawWrappedPanelForPrinting(Graphics g, int canvasWidth,
458           int canvasHeight, int startRes)
459   {
460     SequenceGroup group = av.getSelectionGroup();
461
462     drawWrappedPanel(g, canvasWidth, canvasHeight, startRes);
463
464     if (group != null)
465     {
466       BufferedImage selectImage = null;
467       try
468       {
469         selectImage = new BufferedImage(canvasWidth, canvasHeight,
470                 BufferedImage.TYPE_INT_ARGB); // ARGB so alpha compositing works
471       } catch (OutOfMemoryError er)
472       {
473         System.gc();
474         System.err.println("Print image OutOfMemory Error.\n" + er);
475         new OOMWarning("Creating wrapped alignment image for printing", er);
476       }
477       if (selectImage != null)
478       {
479         Graphics2D g2 = selectImage.createGraphics();
480         setupSelectionGroup(g2, selectImage);
481         drawWrappedSelection(g2, group, canvasWidth, canvasHeight,
482                 startRes);
483
484         g2.setComposite(
485                 AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
486         g.drawImage(selectImage, 0, 0, this);
487         g2.dispose();
488       }
489     }
490   }
491
492   /*
493    * Make a local image by combining the cached image img
494    * with any selection
495    */
496   private BufferedImage buildLocalImage(BufferedImage selectImage)
497   {
498     // clone the cached image
499     BufferedImage lcimg = new BufferedImage(img.getWidth(), img.getHeight(),
500             img.getType());
501     Graphics2D g2d = lcimg.createGraphics();
502     g2d.drawImage(img, 0, 0, null);
503
504     // overlay selection group on lcimg
505     if (selectImage != null)
506     {
507       g2d.setComposite(
508               AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
509       g2d.drawImage(selectImage, 0, 0, this);
510     }
511     g2d.dispose();
512
513     return lcimg;
514   }
515
516   /*
517    * Set up a buffered image of the correct height and size for the sequence canvas
518    */
519   private BufferedImage setupImage()
520   {
521     BufferedImage lcimg = null;
522
523     int charWidth = av.getCharWidth();
524     int charHeight = av.getCharHeight();
525     
526     int width = getWidth();
527     int height = getHeight();
528
529     width -= (width % charWidth);
530     height -= (height % charHeight);
531
532     if ((width < 1) || (height < 1))
533     {
534       return null;
535     }
536
537     try
538     {
539       lcimg = new BufferedImage(width, height,
540               BufferedImage.TYPE_INT_ARGB); // ARGB so alpha compositing works
541     } catch (OutOfMemoryError er)
542     {
543       System.gc();
544       System.err.println(
545               "Group image OutOfMemory Redraw Error.\n" + er);
546       new OOMWarning("Creating alignment image for display", er);
547
548       return null;
549     }
550
551     return lcimg;
552   }
553
554   /**
555    * Returns the visible width of the canvas in residues, after allowing for
556    * East or West scales (if shown)
557    * 
558    * @param canvasWidth
559    *          the width in pixels (possibly including scales)
560    * 
561    * @return
562    */
563   public int getWrappedCanvasWidth(int canvasWidth)
564   {
565     int charWidth = av.getCharWidth();
566
567     FontMetrics fm = getFontMetrics(av.getFont());
568
569     int labelWidth = 0;
570     
571     if (av.getScaleRightWrapped() || av.getScaleLeftWrapped())
572     {
573       labelWidth = getLabelWidth(fm);
574     }
575
576     labelWidthEast = av.getScaleRightWrapped() ? labelWidth : 0;
577
578     labelWidthWest = av.getScaleLeftWrapped() ? labelWidth : 0;
579
580     return (canvasWidth - labelWidthEast - labelWidthWest) / charWidth;
581   }
582
583   /**
584    * Returns a pixel width sufficient to show the largest sequence coordinate
585    * (end position) in the alignment, calculated as the FontMetrics width of
586    * zeroes "0000000" limited to the number of decimal digits to be shown (3 for
587    * 1-10, 4 for 11-99 etc). One character width is added to this, to allow for
588    * half a character width space on either side.
589    * 
590    * @param fm
591    * @return
592    */
593   protected int getLabelWidth(FontMetrics fm)
594   {
595     /*
596      * find the biggest sequence end position we need to show
597      * (note this is not necessarily the sequence length)
598      */
599     int maxWidth = 0;
600     AlignmentI alignment = av.getAlignment();
601     for (int i = 0; i < alignment.getHeight(); i++)
602     {
603       maxWidth = Math.max(maxWidth, alignment.getSequenceAt(i).getEnd());
604     }
605
606     int length = 0;
607     for (int i = maxWidth; i > 0; i /= 10)
608     {
609       length++;
610     }
611
612     return fm.stringWidth(ZEROS.substring(0, length)) + av.getCharWidth();
613   }
614
615   /**
616    * Draws as many widths of a wrapped alignment as can fit in the visible
617    * window
618    * 
619    * @param g
620    * @param canvasWidth
621    *          available width in pixels
622    * @param canvasHeight
623    *          available height in pixels
624    * @param startColumn
625    *          the first column (0...) of the alignment to draw
626    */
627   public void drawWrappedPanel(Graphics g, int canvasWidth,
628           int canvasHeight, final int startColumn)
629   {
630     int wrappedWidthInResidues = calculateWrappedGeometry(canvasWidth,
631             canvasHeight);
632
633     av.setWrappedWidth(wrappedWidthInResidues);
634
635     ViewportRanges ranges = av.getRanges();
636     ranges.setViewportStartAndWidth(startColumn, wrappedWidthInResidues);
637
638     /*
639      * draw one width at a time (including any scales or annotation shown),
640      * until we have run out of either alignment or vertical space available
641      */
642     int ypos = wrappedSpaceAboveAlignment;
643     int maxWidth = ranges.getVisibleAlignmentWidth();
644
645     int start = startColumn;
646     int currentWidth = 0;
647     while ((currentWidth < wrappedVisibleWidths) && (start < maxWidth))
648     {
649       int endColumn = Math
650               .min(maxWidth, start + wrappedWidthInResidues - 1);
651       drawWrappedWidth(g, ypos, start, endColumn, canvasHeight);
652       ypos += wrappedRepeatHeightPx;
653       start += wrappedWidthInResidues;
654       currentWidth++;
655     }
656
657     drawWrappedDecorators(g, startColumn);
658   }
659
660   /**
661    * Calculates and saves values needed when rendering a wrapped alignment.
662    * These depend on many factors, including
663    * <ul>
664    * <li>canvas width and height</li>
665    * <li>number of visible sequences, and height of annotations if shown</li>
666    * <li>font and character width</li>
667    * <li>whether scales are shown left, right or above the alignment</li>
668    * </ul>
669    * 
670    * @param canvasWidth
671    * @param canvasHeight
672    * @return the number of residue columns in each width
673    */
674   protected int calculateWrappedGeometry(int canvasWidth, int canvasHeight)
675   {
676     int charHeight = av.getCharHeight();
677
678     /*
679      * vertical space in pixels between wrapped widths of alignment
680      * - one character height, or two if scale above is drawn
681      */
682     wrappedSpaceAboveAlignment = charHeight
683             * (av.getScaleAboveWrapped() ? 2 : 1);
684
685     /*
686      * height in pixels of the wrapped widths
687      */
688     wrappedRepeatHeightPx = wrappedSpaceAboveAlignment;
689     // add sequences
690     wrappedRepeatHeightPx += av.getRanges().getViewportHeight()
691             * charHeight;
692     // add annotations panel height if shown
693     wrappedRepeatHeightPx += getAnnotationHeight();
694
695     /*
696      * number of visible widths (the last one may be part height),
697      * ensuring a part height includes at least one sequence
698      */
699     ViewportRanges ranges = av.getRanges();
700     int xMax = ranges.getVisibleAlignmentWidth();
701     wrappedVisibleWidths = canvasHeight / wrappedRepeatHeightPx;
702     int remainder = canvasHeight % wrappedRepeatHeightPx;
703     if (remainder >= (wrappedSpaceAboveAlignment + charHeight))
704     {
705       wrappedVisibleWidths++;
706     }
707
708     /*
709      * compute width in residues; this also sets East and West label widths
710      */
711     int wrappedWidthInResidues = getWrappedCanvasWidth(canvasWidth);
712
713     /*
714      *  limit visibleWidths to not exceed width of alignment
715      */
716     int maxWidths = (xMax - ranges.getStartRes()) / wrappedWidthInResidues;
717     if (xMax % wrappedWidthInResidues > 0)
718     {
719       maxWidths++;
720     }
721     wrappedVisibleWidths = Math.min(wrappedVisibleWidths, maxWidths);
722
723     return wrappedWidthInResidues;
724   }
725
726   /**
727    * Draws one width of a wrapped alignment, including sequences and
728    * annnotations, if shown, but not scales or hidden column markers
729    * 
730    * @param g
731    * @param ypos
732    * @param startColumn
733    * @param endColumn
734    * @param canvasHeight
735    */
736   protected void drawWrappedWidth(Graphics g, int ypos, int startColumn,
737           int endColumn, int canvasHeight)
738   {
739     ViewportRanges ranges = av.getRanges();
740     int viewportWidth = ranges.getViewportWidth();
741
742     int endx = Math.min(startColumn + viewportWidth - 1, endColumn);
743
744     /*
745      * move right before drawing by the width of the scale left (if any)
746      * plus column offset from left margin (usually zero, but may be non-zero
747      * when fast painting is drawing just a few columns)
748      */
749     int charWidth = av.getCharWidth();
750     int xOffset = labelWidthWest
751             + ((startColumn - ranges.getStartRes()) % viewportWidth)
752             * charWidth;
753     g.translate(xOffset, 0);
754
755     // When printing we have an extra clipped region,
756     // the Printable page which we need to account for here
757     Shape clip = g.getClip();
758
759     if (clip == null)
760     {
761       g.setClip(0, 0, viewportWidth * charWidth, canvasHeight);
762     }
763     else
764     {
765       g.setClip(0, (int) clip.getBounds().getY(),
766               viewportWidth * charWidth, (int) clip.getBounds().getHeight());
767     }
768
769     /*
770      * white fill the region to be drawn (so incremental fast paint doesn't
771      * scribble over an existing image)
772      */
773     gg.setColor(Color.white);
774     gg.fillRect(0, ypos, (endx - startColumn + 1) * charWidth,
775             wrappedRepeatHeightPx);
776
777     drawPanel(g, startColumn, endx, 0, av.getAlignment().getHeight() - 1,
778             ypos);
779
780     int cHeight = av.getAlignment().getHeight() * av.getCharHeight();
781
782     if (av.isShowAnnotation())
783     {
784       g.translate(0, cHeight + ypos + 3);
785       if (annotations == null)
786       {
787         annotations = new AnnotationPanel(av);
788       }
789
790       annotations.renderer.drawComponent(annotations, av, g, -1,
791               startColumn, endx + 1);
792       g.translate(0, -cHeight - ypos - 3);
793     }
794     g.setClip(clip);
795     g.translate(-xOffset, 0);
796   }
797
798   /**
799    * Draws scales left, right and above (if shown), and any hidden column
800    * markers, on all widths of the wrapped alignment
801    * 
802    * @param g
803    * @param startColumn
804    */
805   protected void drawWrappedDecorators(Graphics g, final int startColumn)
806   {
807     int charWidth = av.getCharWidth();
808
809     g.setFont(av.getFont());
810     g.setColor(Color.black);
811
812     int ypos = wrappedSpaceAboveAlignment;
813     ViewportRanges ranges = av.getRanges();
814     int viewportWidth = ranges.getViewportWidth();
815     int maxWidth = ranges.getVisibleAlignmentWidth();
816     int widthsDrawn = 0;
817     int startCol = startColumn;
818
819     while (widthsDrawn < wrappedVisibleWidths)
820     {
821       int endColumn = Math.min(maxWidth, startCol + viewportWidth - 1);
822
823       if (av.getScaleLeftWrapped())
824       {
825         drawVerticalScale(g, startCol, endColumn - 1, ypos, true);
826       }
827
828       if (av.getScaleRightWrapped())
829       {
830         int x = labelWidthWest + viewportWidth * charWidth;
831         g.translate(x, 0);
832         drawVerticalScale(g, startCol, endColumn, ypos, false);
833         g.translate(-x, 0);
834       }
835
836       /*
837        * white fill region of scale above and hidden column markers
838        * (to support incremental fast paint of image)
839        */
840       g.setColor(Color.white);
841       g.fillRect(0, ypos - wrappedSpaceAboveAlignment, viewportWidth
842               * charWidth + labelWidthWest, wrappedSpaceAboveAlignment);
843       g.setColor(Color.black);
844
845       g.translate(labelWidthWest, 0);
846
847       if (av.getScaleAboveWrapped())
848       {
849         drawNorthScale(g, startCol, endColumn, ypos);
850       }
851
852       if (av.hasHiddenColumns() && av.getShowHiddenMarkers())
853       {
854         drawHiddenColumnMarkers(g, ypos, startCol, endColumn);
855       }
856
857       g.translate(-labelWidthWest, 0);
858
859       ypos += wrappedRepeatHeightPx;
860       startCol += viewportWidth;
861       widthsDrawn++;
862     }
863   }
864
865   /**
866    * @param g
867    * @param ypos
868    * @param startColumn
869    * @param endColumn
870    */
871   protected void drawHiddenColumnMarkers(Graphics g, int ypos,
872           int startColumn, int endColumn)
873   {
874     int charHeight = av.getCharHeight();
875     int charWidth = av.getCharWidth();
876
877     g.setColor(Color.blue);
878     HiddenColumns hidden = av.getAlignment().getHiddenColumns();
879     List<Integer> positions = hidden.findHiddenRegionPositions();
880     for (int pos : positions)
881     {
882       int res = pos - startColumn;
883
884       if (res < 0 || res > endColumn - startColumn)
885       {
886         continue;
887       }
888
889       /*
890        * draw a downward-pointing triangle at the hidden columns location
891        * (before the following visible column)
892        */
893       int xMiddle = res * charWidth;
894       int[] xPoints = new int[] { xMiddle - charHeight / 4,
895           xMiddle + charHeight / 4, xMiddle };
896       int yTop = ypos - (charHeight / 2);
897       int[] yPoints = new int[] { yTop, yTop, yTop + 8 };
898       g.fillPolygon(xPoints, yPoints, 3);
899     }
900   }
901
902   /*
903    * Draw a selection group over a wrapped alignment
904    */
905   private void drawWrappedSelection(Graphics2D g, SequenceGroup group,
906           int canvasWidth,
907           int canvasHeight, int startRes)
908   {
909         int charHeight = av.getCharHeight();
910         int charWidth = av.getCharWidth();
911           
912     // height gap above each panel
913     int hgap = charHeight;
914     if (av.getScaleAboveWrapped())
915     {
916       hgap += charHeight;
917     }
918
919     int cWidth = (canvasWidth - labelWidthEast - labelWidthWest)
920             / charWidth;
921     int cHeight = av.getAlignment().getHeight() * charHeight;
922
923     int startx = startRes;
924     int endx;
925     int ypos = hgap; // vertical offset
926     int maxwidth = av.getAlignment().getWidth();
927
928     if (av.hasHiddenColumns())
929     {
930       maxwidth = av.getAlignment().getHiddenColumns()
931               .findColumnPosition(maxwidth);
932     }
933
934     // chop the wrapped alignment extent up into panel-sized blocks and treat
935     // each block as if it were a block from an unwrapped alignment
936     while ((ypos <= canvasHeight) && (startx < maxwidth))
937     {
938       // set end value to be start + width, or maxwidth, whichever is smaller
939       endx = startx + cWidth - 1;
940
941       if (endx > maxwidth)
942       {
943         endx = maxwidth;
944       }
945
946       g.translate(labelWidthWest, 0);
947
948       drawUnwrappedSelection(g, group, startx, endx, 0,
949               av.getAlignment().getHeight() - 1,
950               ypos);
951
952       g.translate(-labelWidthWest, 0);
953
954       // update vertical offset
955       ypos += cHeight + getAnnotationHeight() + hgap;
956
957       // update horizontal offset
958       startx += cWidth;
959     }
960   }
961
962   int getAnnotationHeight()
963   {
964     if (!av.isShowAnnotation())
965     {
966       return 0;
967     }
968
969     if (annotations == null)
970     {
971       annotations = new AnnotationPanel(av);
972     }
973
974     return annotations.adjustPanelHeight();
975   }
976
977   /**
978    * Draws the visible region of the alignment on the graphics context. If there
979    * are hidden column markers in the visible region, then each sub-region
980    * between the markers is drawn separately, followed by the hidden column
981    * marker.
982    * 
983    * @param g1
984    *          the graphics context, positioned at the first residue to be drawn
985    * @param startRes
986    *          offset of the first column to draw (0..)
987    * @param endRes
988    *          offset of the last column to draw (0..)
989    * @param startSeq
990    *          offset of the first sequence to draw (0..)
991    * @param endSeq
992    *          offset of the last sequence to draw (0..)
993    * @param yOffset
994    *          vertical offset at which to draw (for wrapped alignments)
995    */
996   public void drawPanel(Graphics g1, final int startRes, final int endRes,
997           final int startSeq, final int endSeq, final int yOffset)
998   {
999     int charHeight = av.getCharHeight();
1000     int charWidth = av.getCharWidth();
1001
1002     if (!av.hasHiddenColumns())
1003     {
1004       draw(g1, startRes, endRes, startSeq, endSeq, yOffset);
1005     }
1006     else
1007     {
1008       int screenY = 0;
1009       final int screenYMax = endRes - startRes;
1010       int blockStart = startRes;
1011       int blockEnd = endRes;
1012
1013       for (int[] region : av.getAlignment().getHiddenColumns()
1014               .getHiddenColumnsCopy())
1015       {
1016         int hideStart = region[0];
1017         int hideEnd = region[1];
1018
1019         if (hideStart <= blockStart)
1020         {
1021           blockStart += (hideEnd - hideStart) + 1;
1022           continue;
1023         }
1024
1025         /*
1026          * draw up to just before the next hidden region, or the end of
1027          * the visible region, whichever comes first
1028          */
1029         blockEnd = Math.min(hideStart - 1, blockStart + screenYMax
1030                 - screenY);
1031
1032         g1.translate(screenY * charWidth, 0);
1033
1034         draw(g1, blockStart, blockEnd, startSeq, endSeq, yOffset);
1035
1036         /*
1037          * draw the downline of the hidden column marker (ScalePanel draws the
1038          * triangle on top) if we reached it
1039          */
1040         if (av.getShowHiddenMarkers() && blockEnd == hideStart - 1)
1041         {
1042           g1.setColor(Color.blue);
1043
1044           g1.drawLine((blockEnd - blockStart + 1) * charWidth - 1,
1045                   0 + yOffset, (blockEnd - blockStart + 1) * charWidth - 1,
1046                   (endSeq - startSeq + 1) * charHeight + yOffset);
1047         }
1048
1049         g1.translate(-screenY * charWidth, 0);
1050         screenY += blockEnd - blockStart + 1;
1051         blockStart = hideEnd + 1;
1052
1053         if (screenY > screenYMax)
1054         {
1055           // already rendered last block
1056           return;
1057         }
1058       }
1059
1060       if (screenY <= screenYMax)
1061       {
1062         // remaining visible region to render
1063         blockEnd = blockStart + screenYMax - screenY;
1064         g1.translate(screenY * charWidth, 0);
1065         draw(g1, blockStart, blockEnd, startSeq, endSeq, yOffset);
1066
1067         g1.translate(-screenY * charWidth, 0);
1068       }
1069     }
1070
1071   }
1072
1073   /**
1074    * Draws a region of the visible alignment
1075    * 
1076    * @param g1
1077    * @param startRes
1078    *          offset of the first column in the visible region (0..)
1079    * @param endRes
1080    *          offset of the last column in the visible region (0..)
1081    * @param startSeq
1082    *          offset of the first sequence in the visible region (0..)
1083    * @param endSeq
1084    *          offset of the last sequence in the visible region (0..)
1085    * @param yOffset
1086    *          vertical offset at which to draw (for wrapped alignments)
1087    */
1088   private void draw(Graphics g, int startRes, int endRes, int startSeq,
1089           int endSeq, int offset)
1090   {
1091     int charHeight = av.getCharHeight();
1092     int charWidth = av.getCharWidth();
1093
1094     g.setFont(av.getFont());
1095     seqRdr.prepare(g, av.isRenderGaps());
1096
1097     SequenceI nextSeq;
1098
1099     // / First draw the sequences
1100     // ///////////////////////////
1101     for (int i = startSeq; i <= endSeq; i++)
1102     {
1103       nextSeq = av.getAlignment().getSequenceAt(i);
1104       if (nextSeq == null)
1105       {
1106         // occasionally, a race condition occurs such that the alignment row is
1107         // empty
1108         continue;
1109       }
1110       seqRdr.drawSequence(nextSeq, av.getAlignment().findAllGroups(nextSeq),
1111               startRes, endRes, offset + ((i - startSeq) * charHeight));
1112
1113       if (av.isShowSequenceFeatures())
1114       {
1115         fr.drawSequence(g, nextSeq, startRes, endRes,
1116                 offset + ((i - startSeq) * charHeight), false);
1117       }
1118
1119       /*
1120        * highlight search Results once sequence has been drawn
1121        */
1122       if (av.hasSearchResults())
1123       {
1124         SearchResultsI searchResults = av.getSearchResults();
1125         int[] visibleResults = searchResults.getResults(nextSeq,
1126                 startRes, endRes);
1127         if (visibleResults != null)
1128         {
1129           for (int r = 0; r < visibleResults.length; r += 2)
1130           {
1131             seqRdr.drawHighlightedText(nextSeq, visibleResults[r],
1132                     visibleResults[r + 1], (visibleResults[r] - startRes)
1133                             * charWidth, offset
1134                             + ((i - startSeq) * charHeight));
1135           }
1136         }
1137       }
1138
1139       if (av.cursorMode && cursorY == i && cursorX >= startRes
1140               && cursorX <= endRes)
1141       {
1142         seqRdr.drawCursor(nextSeq, cursorX, (cursorX - startRes) * charWidth,
1143                 offset + ((i - startSeq) * charHeight));
1144       }
1145     }
1146
1147     if (av.getSelectionGroup() != null
1148             || av.getAlignment().getGroups().size() > 0)
1149     {
1150       drawGroupsBoundaries(g, startRes, endRes, startSeq, endSeq, offset);
1151     }
1152
1153   }
1154
1155   void drawGroupsBoundaries(Graphics g1, int startRes, int endRes,
1156           int startSeq, int endSeq, int offset)
1157   {
1158     Graphics2D g = (Graphics2D) g1;
1159     //
1160     // ///////////////////////////////////
1161     // Now outline any areas if necessary
1162     // ///////////////////////////////////
1163
1164     SequenceGroup group = null;
1165     int groupIndex = -1;
1166
1167     if (av.getAlignment().getGroups().size() > 0)
1168     {
1169       group = av.getAlignment().getGroups().get(0);
1170       groupIndex = 0;
1171     }
1172
1173     if (group != null)
1174     {
1175       g.setStroke(new BasicStroke());
1176       g.setColor(group.getOutlineColour());
1177       
1178       do
1179       {
1180         drawPartialGroupOutline(g, group, startRes, endRes, startSeq,
1181                 endSeq, offset);
1182
1183         groupIndex++;
1184
1185         g.setStroke(new BasicStroke());
1186
1187         if (groupIndex >= av.getAlignment().getGroups().size())
1188         {
1189           break;
1190         }
1191
1192         group = av.getAlignment().getGroups().get(groupIndex);
1193
1194       } while (groupIndex < av.getAlignment().getGroups().size());
1195
1196     }
1197
1198   }
1199
1200
1201   /*
1202    * Draw the selection group as a separate image and overlay
1203    */
1204   private BufferedImage drawSelectionGroup(int startRes, int endRes,
1205           int startSeq, int endSeq)
1206   {
1207     // get a new image of the correct size
1208     BufferedImage selectionImage = setupImage();
1209
1210     if (selectionImage == null)
1211     {
1212       return null;
1213     }
1214
1215     SequenceGroup group = av.getSelectionGroup();
1216     if (group == null)
1217     {
1218       // nothing to draw
1219       return null;
1220     }
1221
1222     // set up drawing colour
1223     Graphics2D g = (Graphics2D) selectionImage.getGraphics();
1224
1225     setupSelectionGroup(g, selectionImage);
1226
1227     if (!av.getWrapAlignment())
1228     {
1229       drawUnwrappedSelection(g, group, startRes, endRes, startSeq, endSeq,
1230               0);
1231     }
1232     else
1233     {
1234       drawWrappedSelection(g, group, getWidth(), getHeight(),
1235               av.getRanges().getStartRes());
1236     }
1237
1238     g.dispose();
1239     return selectionImage;
1240   }
1241
1242   /*
1243    * Set up graphics for selection group
1244    */
1245   private void setupSelectionGroup(Graphics2D g,
1246           BufferedImage selectionImage)
1247   {
1248     // set background to transparent
1249     g.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f));
1250     g.fillRect(0, 0, selectionImage.getWidth(), selectionImage.getHeight());
1251
1252     // set up foreground to draw red dashed line
1253     g.setComposite(AlphaComposite.Src);
1254     g.setStroke(new BasicStroke(1, BasicStroke.CAP_BUTT,
1255             BasicStroke.JOIN_ROUND, 3f, new float[]
1256     { 5f, 3f }, 0f));
1257     g.setColor(Color.RED);
1258   }
1259
1260   /*
1261    * Draw a selection group over an unwrapped alignment
1262    * @param g graphics object to draw with
1263    * @param group selection group
1264    * @param startRes start residue of area to draw
1265    * @param endRes end residue of area to draw
1266    * @param startSeq start sequence of area to draw
1267    * @param endSeq end sequence of area to draw
1268    * @param offset vertical offset (used when called from wrapped alignment code)
1269    */
1270   private void drawUnwrappedSelection(Graphics2D g, SequenceGroup group,
1271           int startRes, int endRes, int startSeq, int endSeq, int offset)
1272   {
1273         int charWidth = av.getCharWidth();
1274           
1275     if (!av.hasHiddenColumns())
1276     {
1277       drawPartialGroupOutline(g, group, startRes, endRes, startSeq, endSeq,
1278               offset);
1279     }
1280     else
1281     {
1282       // package into blocks of visible columns
1283       int screenY = 0;
1284       int blockStart = startRes;
1285       int blockEnd = endRes;
1286
1287       for (int[] region : av.getAlignment().getHiddenColumns()
1288               .getHiddenColumnsCopy())
1289       {
1290         int hideStart = region[0];
1291         int hideEnd = region[1];
1292
1293         if (hideStart <= blockStart)
1294         {
1295           blockStart += (hideEnd - hideStart) + 1;
1296           continue;
1297         }
1298
1299         blockEnd = hideStart - 1;
1300
1301         g.translate(screenY * charWidth, 0);
1302         drawPartialGroupOutline(g, group,
1303                 blockStart, blockEnd, startSeq, endSeq, offset);
1304
1305         g.translate(-screenY * charWidth, 0);
1306         screenY += blockEnd - blockStart + 1;
1307         blockStart = hideEnd + 1;
1308
1309         if (screenY > (endRes - startRes))
1310         {
1311           // already rendered last block
1312           break;
1313         }
1314       }
1315
1316       if (screenY <= (endRes - startRes))
1317       {
1318         // remaining visible region to render
1319         blockEnd = blockStart + (endRes - startRes) - screenY;
1320         g.translate(screenY * charWidth, 0);
1321         drawPartialGroupOutline(g, group,
1322                 blockStart, blockEnd, startSeq, endSeq, offset);
1323         
1324         g.translate(-screenY * charWidth, 0);
1325       }
1326     }
1327   }
1328
1329   /*
1330    * Draw the selection group as a separate image and overlay
1331    */
1332   private void drawPartialGroupOutline(Graphics2D g, SequenceGroup group,
1333           int startRes, int endRes, int startSeq, int endSeq,
1334           int verticalOffset)
1335   {
1336         int charHeight = av.getCharHeight();
1337         int charWidth = av.getCharWidth();
1338           
1339     int visWidth = (endRes - startRes + 1) * charWidth;
1340
1341     int oldY = -1;
1342     int i = 0;
1343     boolean inGroup = false;
1344     int top = -1;
1345     int bottom = -1;
1346
1347     int sx = -1;
1348     int sy = -1;
1349     int xwidth = -1;
1350
1351     for (i = startSeq; i <= endSeq; i++)
1352     {
1353       // position of start residue of group relative to startRes, in pixels
1354       sx = (group.getStartRes() - startRes) * charWidth;
1355
1356       // width of group in pixels
1357       xwidth = (((group.getEndRes() + 1) - group.getStartRes()) * charWidth)
1358               - 1;
1359
1360       sy = verticalOffset + (i - startSeq) * charHeight;
1361
1362       if (sx + xwidth < 0 || sx > visWidth)
1363       {
1364         continue;
1365       }
1366
1367       if ((sx <= (endRes - startRes) * charWidth)
1368               && group.getSequences(null)
1369                       .contains(av.getAlignment().getSequenceAt(i)))
1370       {
1371         if ((bottom == -1) && !group.getSequences(null)
1372                 .contains(av.getAlignment().getSequenceAt(i + 1)))
1373         {
1374           bottom = sy + charHeight;
1375         }
1376
1377         if (!inGroup)
1378         {
1379           if (((top == -1) && (i == 0)) || !group.getSequences(null)
1380                   .contains(av.getAlignment().getSequenceAt(i - 1)))
1381           {
1382             top = sy;
1383           }
1384
1385           oldY = sy;
1386           inGroup = true;
1387         }
1388       }
1389       else
1390       {
1391         if (inGroup)
1392         {
1393           // if start position is visible, draw vertical line to left of
1394           // group
1395           if (sx >= 0 && sx < visWidth)
1396           {
1397             g.drawLine(sx, oldY, sx, sy);
1398           }
1399
1400           // if end position is visible, draw vertical line to right of
1401           // group
1402           if (sx + xwidth < visWidth)
1403           {
1404             g.drawLine(sx + xwidth, oldY, sx + xwidth, sy);
1405           }
1406
1407           if (sx < 0)
1408           {
1409             xwidth += sx;
1410             sx = 0;
1411           }
1412
1413           // don't let width extend beyond current block, or group extent
1414           // fixes JAL-2672
1415           if (sx + xwidth >= (endRes - startRes + 1) * charWidth)
1416           {
1417             xwidth = (endRes - startRes + 1) * charWidth - sx;
1418           }
1419           
1420           // draw horizontal line at top of group
1421           if (top != -1)
1422           {
1423             g.drawLine(sx, top, sx + xwidth, top);
1424             top = -1;
1425           }
1426
1427           // draw horizontal line at bottom of group
1428           if (bottom != -1)
1429           {
1430             g.drawLine(sx, bottom, sx + xwidth, bottom);
1431             bottom = -1;
1432           }
1433
1434           inGroup = false;
1435         }
1436       }
1437     }
1438
1439     if (inGroup)
1440     {
1441       sy = verticalOffset + ((i - startSeq) * charHeight);
1442       if (sx >= 0 && sx < visWidth)
1443       {
1444         g.drawLine(sx, oldY, sx, sy);
1445       }
1446
1447       if (sx + xwidth < visWidth)
1448       {
1449         g.drawLine(sx + xwidth, oldY, sx + xwidth, sy);
1450       }
1451
1452       if (sx < 0)
1453       {
1454         xwidth += sx;
1455         sx = 0;
1456       }
1457
1458       if (sx + xwidth > visWidth)
1459       {
1460         xwidth = visWidth;
1461       }
1462       else if (sx + xwidth >= (endRes - startRes + 1) * charWidth)
1463       {
1464         xwidth = (endRes - startRes + 1) * charWidth;
1465       }
1466
1467       if (top != -1)
1468       {
1469         g.drawLine(sx, top, sx + xwidth, top);
1470         top = -1;
1471       }
1472
1473       if (bottom != -1)
1474       {
1475         g.drawLine(sx, bottom - 1, sx + xwidth, bottom - 1);
1476         bottom = -1;
1477       }
1478
1479       inGroup = false;
1480     }
1481   }
1482   
1483   /**
1484    * Highlights search results in the visible region by rendering as white text
1485    * on a black background. Any previous highlighting is removed. Answers true
1486    * if any highlight was left on the visible alignment (so status bar should be
1487    * set to match), else false.
1488    * <p>
1489    * Currently fastPaint is not implemented for wrapped alignments. If a wrapped
1490    * alignment had to be scrolled to show the highlighted region, then it should
1491    * be fully redrawn, otherwise a fast paint can be performed. This argument
1492    * could be removed if fast paint of scrolled wrapped alignment is coded in
1493    * future (JAL-2609).
1494    * 
1495    * @param results
1496    * @param noFastPaint
1497    * @return
1498    */
1499   public boolean highlightSearchResults(SearchResultsI results,
1500           boolean noFastPaint)
1501   {
1502     if (fastpainting)
1503     {
1504       return false;
1505     }
1506     boolean wrapped = av.getWrapAlignment();
1507     try
1508     {
1509       fastPaint = !noFastPaint;
1510       fastpainting = fastPaint;
1511
1512       /*
1513        * to avoid redrawing the whole visible region, we instead
1514        * redraw just the minimal regions to remove previous highlights
1515        * and add new ones
1516        */
1517       SearchResultsI previous = av.getSearchResults();
1518       av.setSearchResults(results);
1519       boolean redrawn = false;
1520       boolean drawn = false;
1521       if (wrapped)
1522       {
1523         redrawn = drawMappedPositionsWrapped(previous);
1524         drawn = drawMappedPositionsWrapped(results);
1525         redrawn |= drawn;
1526       }
1527       else
1528       {
1529         redrawn = drawMappedPositions(previous);
1530         drawn = drawMappedPositions(results);
1531         redrawn |= drawn;
1532       }
1533
1534       /*
1535        * if highlights were either removed or added, repaint
1536        */
1537       if (redrawn)
1538       {
1539         repaint();
1540       }
1541
1542       /*
1543        * return true only if highlights were added
1544        */
1545       return drawn;
1546
1547     } finally
1548     {
1549       fastpainting = false;
1550     }
1551   }
1552
1553   /**
1554    * Redraws the minimal rectangle in the visible region (if any) that includes
1555    * mapped positions of the given search results. Whether or not positions are
1556    * highlighted depends on the SearchResults set on the Viewport. This allows
1557    * this method to be called to either clear or set highlighting. Answers true
1558    * if any positions were drawn (in which case a repaint is still required),
1559    * else false.
1560    * 
1561    * @param results
1562    * @return
1563    */
1564   protected boolean drawMappedPositions(SearchResultsI results)
1565   {
1566     if (results == null)
1567     {
1568       return false;
1569     }
1570
1571     /*
1572      * calculate the minimal rectangle to redraw that 
1573      * includes both new and existing search results
1574      */
1575     int firstSeq = Integer.MAX_VALUE;
1576     int lastSeq = -1;
1577     int firstCol = Integer.MAX_VALUE;
1578     int lastCol = -1;
1579     boolean matchFound = false;
1580
1581     ViewportRanges ranges = av.getRanges();
1582     int firstVisibleColumn = ranges.getStartRes();
1583     int lastVisibleColumn = ranges.getEndRes();
1584     AlignmentI alignment = av.getAlignment();
1585     if (av.hasHiddenColumns())
1586     {
1587       firstVisibleColumn = alignment.getHiddenColumns()
1588               .adjustForHiddenColumns(firstVisibleColumn);
1589       lastVisibleColumn = alignment.getHiddenColumns()
1590               .adjustForHiddenColumns(lastVisibleColumn);
1591     }
1592
1593     for (int seqNo = ranges.getStartSeq(); seqNo <= ranges
1594             .getEndSeq(); seqNo++)
1595     {
1596       SequenceI seq = alignment.getSequenceAt(seqNo);
1597
1598       int[] visibleResults = results.getResults(seq, firstVisibleColumn,
1599               lastVisibleColumn);
1600       if (visibleResults != null)
1601       {
1602         for (int i = 0; i < visibleResults.length - 1; i += 2)
1603         {
1604           int firstMatchedColumn = visibleResults[i];
1605           int lastMatchedColumn = visibleResults[i + 1];
1606           if (firstMatchedColumn <= lastVisibleColumn
1607                   && lastMatchedColumn >= firstVisibleColumn)
1608           {
1609             /*
1610              * found a search results match in the visible region - 
1611              * remember the first and last sequence matched, and the first
1612              * and last visible columns in the matched positions
1613              */
1614             matchFound = true;
1615             firstSeq = Math.min(firstSeq, seqNo);
1616             lastSeq = Math.max(lastSeq, seqNo);
1617             firstMatchedColumn = Math.max(firstMatchedColumn,
1618                     firstVisibleColumn);
1619             lastMatchedColumn = Math.min(lastMatchedColumn,
1620                     lastVisibleColumn);
1621             firstCol = Math.min(firstCol, firstMatchedColumn);
1622             lastCol = Math.max(lastCol, lastMatchedColumn);
1623           }
1624         }
1625       }
1626     }
1627
1628     if (matchFound)
1629     {
1630       if (av.hasHiddenColumns())
1631       {
1632         firstCol = alignment.getHiddenColumns()
1633                 .findColumnPosition(firstCol);
1634         lastCol = alignment.getHiddenColumns().findColumnPosition(lastCol);
1635       }
1636       int transX = (firstCol - ranges.getStartRes()) * av.getCharWidth();
1637       int transY = (firstSeq - ranges.getStartSeq()) * av.getCharHeight();
1638       gg.translate(transX, transY);
1639       drawPanel(gg, firstCol, lastCol, firstSeq, lastSeq, 0);
1640       gg.translate(-transX, -transY);
1641     }
1642
1643     return matchFound;
1644   }
1645
1646   @Override
1647   public void propertyChange(PropertyChangeEvent evt)
1648   {
1649     String eventName = evt.getPropertyName();
1650
1651     if (eventName.equals(SequenceGroup.SEQ_GROUP_CHANGED))
1652     {
1653       fastPaint = true;
1654       repaint();
1655     }
1656     else if (eventName.equals(ViewportRanges.STARTRES))
1657     {
1658       int scrollX = 0;
1659       if (eventName.equals(ViewportRanges.STARTRES))
1660       {
1661         // Make sure we're not trying to draw a panel
1662         // larger than the visible window
1663         ViewportRanges vpRanges = av.getRanges();
1664         scrollX = (int) evt.getNewValue() - (int) evt.getOldValue();
1665         int range = vpRanges.getEndRes() - vpRanges.getStartRes();
1666         if (scrollX > range)
1667         {
1668           scrollX = range;
1669         }
1670         else if (scrollX < -range)
1671         {
1672           scrollX = -range;
1673         }
1674
1675         // Both scrolling and resizing change viewport ranges: scrolling changes
1676         // both start and end points, but resize only changes end values.
1677         // Here we only want to fastpaint on a scroll, with resize using a normal
1678         // paint, so scroll events are identified as changes to the horizontal or
1679         // vertical start value.
1680         
1681         // scroll - startres and endres both change
1682           if (av.getWrapAlignment())
1683         {
1684           fastPaintWrapped(scrollX);
1685         }
1686         else
1687         {
1688           fastPaint(scrollX, 0);
1689         }
1690       }
1691       else if (eventName.equals(ViewportRanges.STARTSEQ))
1692       {
1693         // scroll
1694         fastPaint(0, (int) evt.getNewValue() - (int) evt.getOldValue());
1695       }
1696     }
1697   }
1698
1699   /**
1700    * Does a minimal update of the image for a scroll movement. This method
1701    * handles scroll movements of up to one width of the wrapped alignment (one
1702    * click in the vertical scrollbar). Larger movements (for example after a
1703    * scroll to highlight a mapped position) trigger a full redraw instead.
1704    * 
1705    * @param scrollX
1706    *          number of positions scrolled (right if positive, left if negative)
1707    */
1708   protected void fastPaintWrapped(int scrollX)
1709   {
1710     ViewportRanges ranges = av.getRanges();
1711
1712     if (Math.abs(scrollX) > ranges.getViewportWidth())
1713     {
1714       /*
1715        * shift of more than one view width is 
1716        * overcomplicated to handle in this method
1717        */
1718       fastPaint = false;
1719       repaint();
1720       return;
1721     }
1722
1723     if (fastpainting || gg == null)
1724     {
1725       return;
1726     }
1727
1728     fastPaint = true;
1729     fastpainting = true;
1730
1731     try
1732     {
1733       calculateWrappedGeometry(getWidth(), getHeight());
1734
1735       /*
1736        * relocate the regions of the alignment that are still visible
1737        */
1738       shiftWrappedAlignment(-scrollX);
1739
1740       /*
1741        * add new columns (sequence, annotation)
1742        * - at top left if scrollX < 0 
1743        * - at right of last two widths if scrollX > 0
1744        */
1745       if (scrollX < 0)
1746       {
1747         int startRes = ranges.getStartRes();
1748         drawWrappedWidth(gg, wrappedSpaceAboveAlignment, startRes, startRes
1749                 - scrollX - 1, getHeight());
1750       }
1751       else
1752       {
1753         fastPaintWrappedAddRight(scrollX);
1754       }
1755
1756       /*
1757        * draw all scales (if  shown) and hidden column markers
1758        */
1759       drawWrappedDecorators(gg, ranges.getStartRes());
1760
1761       repaint();
1762     } finally
1763     {
1764       fastpainting = false;
1765     }
1766   }
1767
1768   /**
1769    * Draws the specified number of columns at the 'end' (bottom right) of a
1770    * wrapped alignment view, including sequences and annotations if shown, but
1771    * not scales. Also draws the same number of columns at the right hand end of
1772    * the second last width shown, if the last width is not full height (so
1773    * cannot simply be copied from the graphics image).
1774    * 
1775    * @param columns
1776    */
1777   protected void fastPaintWrappedAddRight(int columns)
1778   {
1779     if (columns == 0)
1780     {
1781       return;
1782     }
1783
1784     ViewportRanges ranges = av.getRanges();
1785     int viewportWidth = ranges.getViewportWidth();
1786     int charWidth = av.getCharWidth();
1787
1788     /**
1789      * draw full height alignment in the second last row, last columns, if the
1790      * last row was not full height
1791      */
1792     int visibleWidths = wrappedVisibleWidths;
1793     int canvasHeight = getHeight();
1794     boolean lastWidthPartHeight = (wrappedVisibleWidths * wrappedRepeatHeightPx) > canvasHeight;
1795
1796     if (lastWidthPartHeight)
1797     {
1798       int widthsAbove = Math.max(0, visibleWidths - 2);
1799       int ypos = wrappedRepeatHeightPx * widthsAbove
1800               + wrappedSpaceAboveAlignment;
1801       int endRes = ranges.getEndRes();
1802       endRes += widthsAbove * viewportWidth;
1803       int startRes = endRes - columns;
1804       int xOffset = ((startRes - ranges.getStartRes()) % viewportWidth)
1805               * charWidth;
1806
1807       /*
1808        * white fill first to erase annotations
1809        */
1810       gg.translate(xOffset, 0);
1811       gg.setColor(Color.white);
1812       gg.fillRect(labelWidthWest, ypos,
1813               (endRes - startRes + 1) * charWidth, wrappedRepeatHeightPx);
1814       gg.translate(-xOffset, 0);
1815
1816       drawWrappedWidth(gg, ypos, startRes, endRes, canvasHeight);
1817     }
1818
1819     /*
1820      * draw newly visible columns in last wrapped width (none if we
1821      * have reached the end of the alignment)
1822      * y-offset for drawing last width is height of widths above,
1823      * plus one gap row
1824      */
1825     int widthsAbove = visibleWidths - 1;
1826     int ypos = wrappedRepeatHeightPx * widthsAbove
1827             + wrappedSpaceAboveAlignment;
1828     int endRes = ranges.getEndRes();
1829     endRes += widthsAbove * viewportWidth;
1830     int startRes = endRes - columns + 1;
1831
1832     /*
1833      * white fill first to erase annotations
1834      */
1835     int xOffset = ((startRes - ranges.getStartRes()) % viewportWidth)
1836             * charWidth;
1837     gg.translate(xOffset, 0);
1838     gg.setColor(Color.white);
1839     int width = viewportWidth * charWidth - xOffset;
1840     gg.fillRect(labelWidthWest, ypos, width, wrappedRepeatHeightPx);
1841     gg.translate(-xOffset, 0);
1842
1843     gg.setFont(av.getFont());
1844     gg.setColor(Color.black);
1845
1846     if (startRes < ranges.getVisibleAlignmentWidth())
1847     {
1848       drawWrappedWidth(gg, ypos, startRes, endRes, canvasHeight);
1849     }
1850
1851     /*
1852      * and finally, white fill any space below the visible alignment
1853      */
1854     int heightBelow = canvasHeight - visibleWidths * wrappedRepeatHeightPx;
1855     if (heightBelow > 0)
1856     {
1857       gg.setColor(Color.white);
1858       gg.fillRect(0, canvasHeight - heightBelow, getWidth(), heightBelow);
1859     }
1860   }
1861
1862   /**
1863    * Shifts the visible alignment by the specified number of columns - left if
1864    * negative, right if positive. Copies and moves sequences and annotations (if
1865    * shown). Scales, hidden column markers and any newly visible columns must be
1866    * drawn separately.
1867    * 
1868    * @param positions
1869    */
1870   protected void shiftWrappedAlignment(int positions)
1871   {
1872     if (positions == 0)
1873     {
1874       return;
1875     }
1876     int charWidth = av.getCharWidth();
1877
1878     int canvasHeight = getHeight();
1879     ViewportRanges ranges = av.getRanges();
1880     int viewportWidth = ranges.getViewportWidth();
1881     int widthToCopy = (ranges.getViewportWidth() - Math.abs(positions))
1882             * charWidth;
1883     int heightToCopy = wrappedRepeatHeightPx - wrappedSpaceAboveAlignment;
1884     int xMax = ranges.getVisibleAlignmentWidth();
1885
1886     if (positions > 0)
1887     {
1888       /*
1889        * shift right (after scroll left)
1890        * for each wrapped width (starting with the last), copy (width-positions) 
1891        * columns from the left margin to the right margin, and copy positions 
1892        * columns from the right margin of the row above (if any) to the 
1893        * left margin of the current row
1894        */
1895
1896       /*
1897        * get y-offset of last wrapped width, first row of sequences
1898        */
1899       int y = canvasHeight / wrappedRepeatHeightPx * wrappedRepeatHeightPx;
1900       y += wrappedSpaceAboveAlignment;
1901       int copyFromLeftStart = labelWidthWest;
1902       int copyFromRightStart = copyFromLeftStart + widthToCopy;
1903
1904       while (y >= 0)
1905       {
1906         gg.copyArea(copyFromLeftStart, y, widthToCopy, heightToCopy,
1907                 positions * charWidth, 0);
1908         if (y > 0)
1909         {
1910           gg.copyArea(copyFromRightStart, y - wrappedRepeatHeightPx,
1911                   positions * charWidth, heightToCopy, -widthToCopy,
1912                   wrappedRepeatHeightPx);
1913         }
1914
1915         y -= wrappedRepeatHeightPx;
1916       }
1917     }
1918     else
1919     {
1920       /*
1921        * shift left (after scroll right)
1922        * for each wrapped width (starting with the first), copy (width-positions) 
1923        * columns from the right margin to the left margin, and copy positions 
1924        * columns from the left margin of the row below (if any) to the 
1925        * right margin of the current row
1926        */
1927       int xpos = av.getRanges().getStartRes();
1928       int y = wrappedSpaceAboveAlignment;
1929       int copyFromRightStart = labelWidthWest - positions * charWidth;
1930
1931       while (y < canvasHeight)
1932       {
1933         gg.copyArea(copyFromRightStart, y, widthToCopy, heightToCopy,
1934                 positions * charWidth, 0);
1935         if (y + wrappedRepeatHeightPx < canvasHeight - wrappedRepeatHeightPx
1936                 && (xpos + viewportWidth <= xMax))
1937         {
1938           gg.copyArea(labelWidthWest, y + wrappedRepeatHeightPx, -positions
1939                   * charWidth, heightToCopy, widthToCopy,
1940                   -wrappedRepeatHeightPx);
1941         }
1942
1943         y += wrappedRepeatHeightPx;
1944         xpos += viewportWidth;
1945       }
1946     }
1947   }
1948
1949   
1950   /**
1951    * Redraws any positions in the search results in the visible region of a
1952    * wrapped alignment. Any highlights are drawn depending on the search results
1953    * set on the Viewport, not the <code>results</code> argument. This allows
1954    * this method to be called either to clear highlights (passing the previous
1955    * search results), or to draw new highlights.
1956    * 
1957    * @param results
1958    * @return
1959    */
1960   protected boolean drawMappedPositionsWrapped(SearchResultsI results)
1961   {
1962     if (results == null)
1963     {
1964       return false;
1965     }
1966     int charHeight = av.getCharHeight();
1967
1968     boolean matchFound = false;
1969
1970     calculateWrappedGeometry(getWidth(), getHeight());
1971     int wrappedWidth = av.getWrappedWidth();
1972     int wrappedHeight = wrappedRepeatHeightPx;
1973
1974     ViewportRanges ranges = av.getRanges();
1975     int canvasHeight = getHeight();
1976     int repeats = canvasHeight / wrappedHeight;
1977     if (canvasHeight / wrappedHeight > 0)
1978     {
1979       repeats++;
1980     }
1981
1982     int firstVisibleColumn = ranges.getStartRes();
1983     int lastVisibleColumn = ranges.getStartRes() + repeats
1984             * ranges.getViewportWidth() - 1;
1985
1986     AlignmentI alignment = av.getAlignment();
1987     if (av.hasHiddenColumns())
1988     {
1989       firstVisibleColumn = alignment.getHiddenColumns()
1990               .adjustForHiddenColumns(firstVisibleColumn);
1991       lastVisibleColumn = alignment.getHiddenColumns()
1992               .adjustForHiddenColumns(lastVisibleColumn);
1993     }
1994
1995     int gapHeight = charHeight * (av.getScaleAboveWrapped() ? 2 : 1);
1996
1997     for (int seqNo = ranges.getStartSeq(); seqNo <= ranges
1998             .getEndSeq(); seqNo++)
1999     {
2000       SequenceI seq = alignment.getSequenceAt(seqNo);
2001
2002       int[] visibleResults = results.getResults(seq, firstVisibleColumn,
2003               lastVisibleColumn);
2004       if (visibleResults != null)
2005       {
2006         for (int i = 0; i < visibleResults.length - 1; i += 2)
2007         {
2008           int firstMatchedColumn = visibleResults[i];
2009           int lastMatchedColumn = visibleResults[i + 1];
2010           if (firstMatchedColumn <= lastVisibleColumn
2011                   && lastMatchedColumn >= firstVisibleColumn)
2012           {
2013             /*
2014              * found a search results match in the visible region
2015              */
2016             firstMatchedColumn = Math.max(firstMatchedColumn,
2017                     firstVisibleColumn);
2018             lastMatchedColumn = Math.min(lastMatchedColumn,
2019                     lastVisibleColumn);
2020
2021             /*
2022              * draw each mapped position separately (as contiguous positions may
2023              * wrap across lines)
2024              */
2025             for (int mappedPos = firstMatchedColumn; mappedPos <= lastMatchedColumn; mappedPos++)
2026             {
2027               int displayColumn = mappedPos;
2028               if (av.hasHiddenColumns())
2029               {
2030                 displayColumn = alignment.getHiddenColumns()
2031                         .findColumnPosition(displayColumn);
2032               }
2033
2034               /*
2035                * transX: offset from left edge of canvas to residue position
2036                */
2037               int transX = labelWidthWest
2038                       + ((displayColumn - ranges.getStartRes()) % wrappedWidth)
2039                       * av.getCharWidth();
2040
2041               /*
2042                * transY: offset from top edge of canvas to residue position
2043                */
2044               int transY = gapHeight;
2045               transY += (displayColumn - ranges.getStartRes())
2046                       / wrappedWidth * wrappedHeight;
2047               transY += (seqNo - ranges.getStartSeq()) * av.getCharHeight();
2048
2049               /*
2050                * yOffset is from graphics origin to start of visible region
2051                */
2052               int yOffset = 0;// (displayColumn / wrappedWidth) * wrappedHeight;
2053               if (transY < getHeight())
2054               {
2055                 matchFound = true;
2056                 gg.translate(transX, transY);
2057                 drawPanel(gg, displayColumn, displayColumn, seqNo, seqNo,
2058                         yOffset);
2059                 gg.translate(-transX, -transY);
2060               }
2061             }
2062           }
2063         }
2064       }
2065     }
2066   
2067     return matchFound;
2068   }
2069
2070   /**
2071    * Answers the width in pixels of the left scale labels (0 if not shown)
2072    * 
2073    * @return
2074    */
2075   int getLabelWidthWest()
2076   {
2077     return labelWidthWest;
2078   }
2079 }