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