JAL-3002 don't use fastPaint for page up/down
[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     /*
656      * draw one width at a time (including any scales or annotation shown),
657      * until we have run out of either alignment or vertical space available
658      */
659     int ypos = wrappedSpaceAboveAlignment;
660     int maxWidth = ranges.getVisibleAlignmentWidth();
661
662     int start = startColumn;
663     int currentWidth = 0;
664     while ((currentWidth < wrappedVisibleWidths) && (start < maxWidth))
665     {
666       int endColumn = Math
667               .min(maxWidth, start + wrappedWidthInResidues - 1);
668       drawWrappedWidth(g, ypos, start, endColumn, canvasHeight);
669       ypos += wrappedRepeatHeightPx;
670       start += wrappedWidthInResidues;
671       currentWidth++;
672     }
673
674     drawWrappedDecorators(g, startColumn);
675   }
676
677   /**
678    * Calculates and saves values needed when rendering a wrapped alignment.
679    * These depend on many factors, including
680    * <ul>
681    * <li>canvas width and height</li>
682    * <li>number of visible sequences, and height of annotations if shown</li>
683    * <li>font and character width</li>
684    * <li>whether scales are shown left, right or above the alignment</li>
685    * </ul>
686    * 
687    * @param canvasWidth
688    * @param canvasHeight
689    * @return the number of residue columns in each width
690    */
691   protected int calculateWrappedGeometry(int canvasWidth, int canvasHeight)
692   {
693     int charHeight = av.getCharHeight();
694
695     /*
696      * vertical space in pixels between wrapped widths of alignment
697      * - one character height, or two if scale above is drawn
698      */
699     wrappedSpaceAboveAlignment = charHeight
700             * (av.getScaleAboveWrapped() ? 2 : 1);
701
702     /*
703      * height in pixels of the wrapped widths
704      */
705     wrappedRepeatHeightPx = wrappedSpaceAboveAlignment;
706     // add sequences
707     wrappedRepeatHeightPx += av.getRanges().getViewportHeight()
708             * charHeight;
709     // add annotations panel height if shown
710     wrappedRepeatHeightPx += getAnnotationHeight();
711
712     /*
713      * number of visible widths (the last one may be part height),
714      * ensuring a part height includes at least one sequence
715      */
716     ViewportRanges ranges = av.getRanges();
717     wrappedVisibleWidths = canvasHeight / wrappedRepeatHeightPx;
718     int remainder = canvasHeight % wrappedRepeatHeightPx;
719     if (remainder >= (wrappedSpaceAboveAlignment + charHeight))
720     {
721       wrappedVisibleWidths++;
722     }
723
724     /*
725      * compute width in residues; this also sets East and West label widths
726      */
727     int wrappedWidthInResidues = getWrappedCanvasWidth(canvasWidth);
728
729     /*
730      *  limit visibleWidths to not exceed width of alignment
731      */
732     int xMax = ranges.getVisibleAlignmentWidth();
733     int startToEnd = xMax - ranges.getStartRes();
734     int maxWidths = startToEnd / wrappedWidthInResidues;
735     if (startToEnd % wrappedWidthInResidues > 0)
736     {
737       maxWidths++;
738     }
739     wrappedVisibleWidths = Math.min(wrappedVisibleWidths, maxWidths);
740
741     return wrappedWidthInResidues;
742   }
743
744   /**
745    * Draws one width of a wrapped alignment, including sequences and
746    * annnotations, if shown, but not scales or hidden column markers
747    * 
748    * @param g
749    * @param ypos
750    * @param startColumn
751    * @param endColumn
752    * @param canvasHeight
753    */
754   protected void drawWrappedWidth(Graphics g, int ypos, int startColumn,
755           int endColumn, int canvasHeight)
756   {
757     ViewportRanges ranges = av.getRanges();
758     int viewportWidth = ranges.getViewportWidth();
759
760     int endx = Math.min(startColumn + viewportWidth - 1, endColumn);
761
762     /*
763      * move right before drawing by the width of the scale left (if any)
764      * plus column offset from left margin (usually zero, but may be non-zero
765      * when fast painting is drawing just a few columns)
766      */
767     int charWidth = av.getCharWidth();
768     int xOffset = labelWidthWest
769             + ((startColumn - ranges.getStartRes()) % viewportWidth)
770             * charWidth;
771     g.translate(xOffset, 0);
772
773     // When printing we have an extra clipped region,
774     // the Printable page which we need to account for here
775     Shape clip = g.getClip();
776
777     if (clip == null)
778     {
779       g.setClip(0, 0, viewportWidth * charWidth, canvasHeight);
780     }
781     else
782     {
783       g.setClip(0, (int) clip.getBounds().getY(),
784               viewportWidth * charWidth, (int) clip.getBounds().getHeight());
785     }
786
787     /*
788      * white fill the region to be drawn (so incremental fast paint doesn't
789      * scribble over an existing image)
790      */
791     g.setColor(Color.white);
792     g.fillRect(0, ypos, (endx - startColumn + 1) * charWidth,
793             wrappedRepeatHeightPx);
794
795     drawPanel(g, startColumn, endx, 0, av.getAlignment().getHeight() - 1,
796             ypos);
797
798     int cHeight = av.getAlignment().getHeight() * av.getCharHeight();
799
800     if (av.isShowAnnotation())
801     {
802       g.translate(0, cHeight + ypos + 3);
803       if (annotations == null)
804       {
805         annotations = new AnnotationPanel(av);
806       }
807
808       annotations.renderer.drawComponent(annotations, av, g, -1,
809               startColumn, endx + 1);
810       g.translate(0, -cHeight - ypos - 3);
811     }
812     g.setClip(clip);
813     g.translate(-xOffset, 0);
814   }
815
816   /**
817    * Draws scales left, right and above (if shown), and any hidden column
818    * markers, on all widths of the wrapped alignment
819    * 
820    * @param g
821    * @param startColumn
822    */
823   protected void drawWrappedDecorators(Graphics g, final int startColumn)
824   {
825     int charWidth = av.getCharWidth();
826
827     g.setFont(av.getFont());
828     g.setColor(Color.black);
829
830     int ypos = wrappedSpaceAboveAlignment;
831     ViewportRanges ranges = av.getRanges();
832     int viewportWidth = ranges.getViewportWidth();
833     int maxWidth = ranges.getVisibleAlignmentWidth();
834     int widthsDrawn = 0;
835     int startCol = startColumn;
836
837     while (widthsDrawn < wrappedVisibleWidths)
838     {
839       int endColumn = Math.min(maxWidth, startCol + viewportWidth - 1);
840
841       if (av.getScaleLeftWrapped())
842       {
843         drawVerticalScale(g, startCol, endColumn - 1, ypos, true);
844       }
845
846       if (av.getScaleRightWrapped())
847       {
848         int x = labelWidthWest + viewportWidth * charWidth;
849         g.translate(x, 0);
850         drawVerticalScale(g, startCol, endColumn, ypos, false);
851         g.translate(-x, 0);
852       }
853
854       /*
855        * white fill region of scale above and hidden column markers
856        * (to support incremental fast paint of image)
857        */
858       g.translate(labelWidthWest, 0);
859       g.setColor(Color.white);
860       g.fillRect(0, ypos - wrappedSpaceAboveAlignment, viewportWidth
861               * charWidth + labelWidthWest, wrappedSpaceAboveAlignment);
862       g.setColor(Color.black);
863       g.translate(-labelWidthWest, 0);
864
865       g.translate(labelWidthWest, 0);
866
867       if (av.getScaleAboveWrapped())
868       {
869         drawNorthScale(g, startCol, endColumn, ypos);
870       }
871
872       if (av.hasHiddenColumns() && av.getShowHiddenMarkers())
873       {
874         drawHiddenColumnMarkers(g, ypos, startCol, endColumn);
875       }
876
877       g.translate(-labelWidthWest, 0);
878
879       ypos += wrappedRepeatHeightPx;
880       startCol += viewportWidth;
881       widthsDrawn++;
882     }
883   }
884
885   /**
886    * Draws markers (triangles) above hidden column positions between startColumn
887    * and endColumn.
888    * 
889    * @param g
890    * @param ypos
891    * @param startColumn
892    * @param endColumn
893    */
894   protected void drawHiddenColumnMarkers(Graphics g, int ypos,
895           int startColumn, int endColumn)
896   {
897     int charHeight = av.getCharHeight();
898     int charWidth = av.getCharWidth();
899
900     g.setColor(Color.blue);
901     int res;
902     HiddenColumns hidden = av.getAlignment().getHiddenColumns();
903
904     Iterator<Integer> it = hidden.getStartRegionIterator(startColumn,
905             endColumn);
906     while (it.hasNext())
907     {
908       res = it.next() - startColumn;
909
910       if (res < 0 || res > endColumn - startColumn + 1)
911       {
912         continue;
913       }
914
915       /*
916        * draw a downward-pointing triangle at the hidden columns location
917        * (before the following visible column)
918        */
919       int xMiddle = res * charWidth;
920       int[] xPoints = new int[] { xMiddle - charHeight / 4,
921           xMiddle + charHeight / 4, xMiddle };
922       int yTop = ypos - (charHeight / 2);
923       int[] yPoints = new int[] { yTop, yTop, yTop + 8 };
924       g.fillPolygon(xPoints, yPoints, 3);
925     }
926   }
927
928   /*
929    * Draw a selection group over a wrapped alignment
930    */
931   private void drawWrappedSelection(Graphics2D g, SequenceGroup group,
932           int canvasWidth,
933           int canvasHeight, int startRes)
934   {
935     int charHeight = av.getCharHeight();
936     int charWidth = av.getCharWidth();
937       
938     // height gap above each panel
939     int hgap = charHeight;
940     if (av.getScaleAboveWrapped())
941     {
942       hgap += charHeight;
943     }
944
945     int cWidth = (canvasWidth - labelWidthEast - labelWidthWest)
946             / charWidth;
947     int cHeight = av.getAlignment().getHeight() * charHeight;
948
949     int startx = startRes;
950     int endx;
951     int ypos = hgap; // vertical offset
952     int maxwidth = av.getAlignment().getWidth();
953
954     if (av.hasHiddenColumns())
955     {
956       maxwidth = av.getAlignment().getHiddenColumns()
957               .absoluteToVisibleColumn(maxwidth);
958     }
959
960     // chop the wrapped alignment extent up into panel-sized blocks and treat
961     // each block as if it were a block from an unwrapped alignment
962     while ((ypos <= canvasHeight) && (startx < maxwidth))
963     {
964       // set end value to be start + width, or maxwidth, whichever is smaller
965       endx = startx + cWidth - 1;
966
967       if (endx > maxwidth)
968       {
969         endx = maxwidth;
970       }
971
972       g.translate(labelWidthWest, 0);
973
974       drawUnwrappedSelection(g, group, startx, endx, 0,
975               av.getAlignment().getHeight() - 1,
976               ypos);
977
978       g.translate(-labelWidthWest, 0);
979
980       // update vertical offset
981       ypos += cHeight + getAnnotationHeight() + hgap;
982
983       // update horizontal offset
984       startx += cWidth;
985     }
986   }
987
988   int getAnnotationHeight()
989   {
990     if (!av.isShowAnnotation())
991     {
992       return 0;
993     }
994
995     if (annotations == null)
996     {
997       annotations = new AnnotationPanel(av);
998     }
999
1000     return annotations.adjustPanelHeight();
1001   }
1002
1003   /**
1004    * Draws the visible region of the alignment on the graphics context. If there
1005    * are hidden column markers in the visible region, then each sub-region
1006    * between the markers is drawn separately, followed by the hidden column
1007    * marker.
1008    * 
1009    * @param g1
1010    *          the graphics context, positioned at the first residue to be drawn
1011    * @param startRes
1012    *          offset of the first column to draw (0..)
1013    * @param endRes
1014    *          offset of the last column to draw (0..)
1015    * @param startSeq
1016    *          offset of the first sequence to draw (0..)
1017    * @param endSeq
1018    *          offset of the last sequence to draw (0..)
1019    * @param yOffset
1020    *          vertical offset at which to draw (for wrapped alignments)
1021    */
1022   public void drawPanel(Graphics g1, final int startRes, final int endRes,
1023           final int startSeq, final int endSeq, final int yOffset)
1024   {
1025     int charHeight = av.getCharHeight();
1026     int charWidth = av.getCharWidth();
1027
1028     if (!av.hasHiddenColumns())
1029     {
1030       draw(g1, startRes, endRes, startSeq, endSeq, yOffset);
1031     }
1032     else
1033     {
1034       int screenY = 0;
1035       int blockStart;
1036       int blockEnd;
1037
1038       HiddenColumns hidden = av.getAlignment().getHiddenColumns();
1039       VisibleContigsIterator regions = hidden
1040               .getVisContigsIterator(startRes, endRes + 1, true);
1041
1042       while (regions.hasNext())
1043       {
1044         int[] region = regions.next();
1045         blockEnd = region[1];
1046         blockStart = region[0];
1047
1048         /*
1049          * draw up to just before the next hidden region, or the end of
1050          * the visible region, whichever comes first
1051          */
1052         g1.translate(screenY * charWidth, 0);
1053
1054         draw(g1, blockStart, blockEnd, startSeq, endSeq, yOffset);
1055
1056         /*
1057          * draw the downline of the hidden column marker (ScalePanel draws the
1058          * triangle on top) if we reached it
1059          */
1060         if (av.getShowHiddenMarkers()
1061                 && (regions.hasNext() || regions.endsAtHidden()))
1062         {
1063           g1.setColor(Color.blue);
1064
1065           g1.drawLine((blockEnd - blockStart + 1) * charWidth - 1,
1066                   0 + yOffset, (blockEnd - blockStart + 1) * charWidth - 1,
1067                   (endSeq - startSeq + 1) * charHeight + yOffset);
1068         }
1069
1070         g1.translate(-screenY * charWidth, 0);
1071         screenY += blockEnd - blockStart + 1;
1072       }
1073     }
1074
1075   }
1076
1077   /**
1078    * Draws a region of the visible alignment
1079    * 
1080    * @param g1
1081    * @param startRes
1082    *          offset of the first column in the visible region (0..)
1083    * @param endRes
1084    *          offset of the last column in the visible region (0..)
1085    * @param startSeq
1086    *          offset of the first sequence in the visible region (0..)
1087    * @param endSeq
1088    *          offset of the last sequence in the visible region (0..)
1089    * @param yOffset
1090    *          vertical offset at which to draw (for wrapped alignments)
1091    */
1092   private void draw(Graphics g, int startRes, int endRes, int startSeq,
1093           int endSeq, int offset)
1094   {
1095     int charHeight = av.getCharHeight();
1096     int charWidth = av.getCharWidth();
1097
1098     g.setFont(av.getFont());
1099     seqRdr.prepare(g, av.isRenderGaps());
1100
1101     SequenceI nextSeq;
1102
1103     // / First draw the sequences
1104     // ///////////////////////////
1105     for (int i = startSeq; i <= endSeq; i++)
1106     {
1107       nextSeq = av.getAlignment().getSequenceAt(i);
1108       if (nextSeq == null)
1109       {
1110         // occasionally, a race condition occurs such that the alignment row is
1111         // empty
1112         continue;
1113       }
1114       seqRdr.drawSequence(nextSeq, av.getAlignment().findAllGroups(nextSeq),
1115               startRes, endRes, offset + ((i - startSeq) * charHeight));
1116
1117       if (av.isShowSequenceFeatures())
1118       {
1119         fr.drawSequence(g, nextSeq, startRes, endRes,
1120                 offset + ((i - startSeq) * charHeight), false);
1121       }
1122
1123       /*
1124        * highlight search Results once sequence has been drawn
1125        */
1126       if (av.hasSearchResults())
1127       {
1128         SearchResultsI searchResults = av.getSearchResults();
1129         int[] visibleResults = searchResults.getResults(nextSeq, startRes,
1130                 endRes);
1131         if (visibleResults != null)
1132         {
1133           for (int r = 0; r < visibleResults.length; r += 2)
1134           {
1135             seqRdr.drawHighlightedText(nextSeq, visibleResults[r],
1136                     visibleResults[r + 1],
1137                     (visibleResults[r] - startRes) * charWidth,
1138                     offset + ((i - startSeq) * charHeight));
1139           }
1140         }
1141       }
1142     }
1143
1144     if (av.getSelectionGroup() != null
1145             || av.getAlignment().getGroups().size() > 0)
1146     {
1147       drawGroupsBoundaries(g, startRes, endRes, startSeq, endSeq, offset);
1148     }
1149
1150   }
1151
1152   void drawGroupsBoundaries(Graphics g1, int startRes, int endRes,
1153           int startSeq, int endSeq, int offset)
1154   {
1155     Graphics2D g = (Graphics2D) g1;
1156     //
1157     // ///////////////////////////////////
1158     // Now outline any areas if necessary
1159     // ///////////////////////////////////
1160
1161     SequenceGroup group = null;
1162     int groupIndex = -1;
1163
1164     if (av.getAlignment().getGroups().size() > 0)
1165     {
1166       group = av.getAlignment().getGroups().get(0);
1167       groupIndex = 0;
1168     }
1169
1170     if (group != null)
1171     {
1172       g.setStroke(new BasicStroke());
1173       g.setColor(group.getOutlineColour());
1174       
1175       do
1176       {
1177         drawPartialGroupOutline(g, group, startRes, endRes, startSeq,
1178                 endSeq, offset);
1179
1180         groupIndex++;
1181
1182         g.setStroke(new BasicStroke());
1183
1184         if (groupIndex >= av.getAlignment().getGroups().size())
1185         {
1186           break;
1187         }
1188
1189         group = av.getAlignment().getGroups().get(groupIndex);
1190
1191       } while (groupIndex < av.getAlignment().getGroups().size());
1192
1193     }
1194
1195   }
1196
1197
1198   /*
1199    * Draw the selection group as a separate image and overlay
1200    */
1201   private BufferedImage drawSelectionGroup(int startRes, int endRes,
1202           int startSeq, int endSeq)
1203   {
1204     // get a new image of the correct size
1205     BufferedImage selectionImage = setupImage();
1206
1207     if (selectionImage == null)
1208     {
1209       return null;
1210     }
1211
1212     SequenceGroup group = av.getSelectionGroup();
1213     if (group == null)
1214     {
1215       // nothing to draw
1216       return null;
1217     }
1218
1219     // set up drawing colour
1220     Graphics2D g = (Graphics2D) selectionImage.getGraphics();
1221
1222     setupSelectionGroup(g, selectionImage);
1223
1224     if (!av.getWrapAlignment())
1225     {
1226       drawUnwrappedSelection(g, group, startRes, endRes, startSeq, endSeq,
1227               0);
1228     }
1229     else
1230     {
1231       drawWrappedSelection(g, group, getWidth(), getHeight(),
1232               av.getRanges().getStartRes());
1233     }
1234
1235     g.dispose();
1236     return selectionImage;
1237   }
1238
1239   /**
1240    * Draw the cursor as a separate image and overlay
1241    * 
1242    * @param startRes
1243    *          start residue of area to draw cursor in
1244    * @param endRes
1245    *          end residue of area to draw cursor in
1246    * @param startSeq
1247    *          start sequence of area to draw cursor in
1248    * @param endSeq
1249    *          end sequence of are to draw cursor in
1250    * @return a transparent image of the same size as the sequence canvas, with
1251    *         the cursor drawn on it, if any
1252    */
1253   private void drawCursor(Graphics g, int startRes, int endRes,
1254           int startSeq,
1255           int endSeq)
1256   {
1257     // convert the cursorY into a position on the visible alignment
1258     int cursor_ypos = cursorY;
1259
1260     // don't do work unless we have to
1261     if (cursor_ypos >= startSeq && cursor_ypos <= endSeq)
1262     {
1263       int yoffset = 0;
1264       int xoffset = 0;
1265       int startx = startRes;
1266       int endx = endRes;
1267
1268       // convert the cursorX into a position on the visible alignment
1269       int cursor_xpos = av.getAlignment().getHiddenColumns()
1270               .absoluteToVisibleColumn(cursorX);
1271
1272       if (av.getAlignment().getHiddenColumns().isVisible(cursorX))
1273       {
1274
1275         if (av.getWrapAlignment())
1276         {
1277           // work out the correct offsets for the cursor
1278           int charHeight = av.getCharHeight();
1279           int charWidth = av.getCharWidth();
1280           int canvasWidth = getWidth();
1281           int canvasHeight = getHeight();
1282
1283           // height gap above each panel
1284           int hgap = charHeight;
1285           if (av.getScaleAboveWrapped())
1286           {
1287             hgap += charHeight;
1288           }
1289
1290           int cWidth = (canvasWidth - labelWidthEast - labelWidthWest)
1291                   / charWidth;
1292           int cHeight = av.getAlignment().getHeight() * charHeight;
1293
1294           endx = startx + cWidth - 1;
1295           int ypos = hgap; // vertical offset
1296
1297           // iterate down the wrapped panels
1298           while ((ypos <= canvasHeight) && (endx < cursor_xpos))
1299           {
1300             // update vertical offset
1301             ypos += cHeight + getAnnotationHeight() + hgap;
1302
1303             // update horizontal offset
1304             startx += cWidth;
1305             endx = startx + cWidth - 1;
1306           }
1307           yoffset = ypos;
1308           xoffset = labelWidthWest;
1309         }
1310
1311         // now check if cursor is within range for x values
1312         if (cursor_xpos >= startx && cursor_xpos <= endx)
1313         {
1314           // get the character the cursor is drawn at
1315           SequenceI seq = av.getAlignment().getSequenceAt(cursorY);
1316           char s = seq.getCharAt(cursorX);
1317
1318           seqRdr.drawCursor(g, s,
1319                   xoffset + (cursor_xpos - startx) * av.getCharWidth(),
1320                   yoffset + (cursor_ypos - startSeq) * av.getCharHeight());
1321         }
1322       }
1323     }
1324   }
1325
1326
1327   /*
1328    * Set up graphics for selection group
1329    */
1330   private void setupSelectionGroup(Graphics2D g,
1331           BufferedImage selectionImage)
1332   {
1333     // set background to transparent
1334     g.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f));
1335     g.fillRect(0, 0, selectionImage.getWidth(), selectionImage.getHeight());
1336
1337     // set up foreground to draw red dashed line
1338     g.setComposite(AlphaComposite.Src);
1339     g.setStroke(new BasicStroke(1, BasicStroke.CAP_BUTT,
1340             BasicStroke.JOIN_ROUND, 3f, new float[]
1341     { 5f, 3f }, 0f));
1342     g.setColor(Color.RED);
1343   }
1344
1345   /*
1346    * Draw a selection group over an unwrapped alignment
1347    * @param g graphics object to draw with
1348    * @param group selection group
1349    * @param startRes start residue of area to draw
1350    * @param endRes end residue of area to draw
1351    * @param startSeq start sequence of area to draw
1352    * @param endSeq end sequence of area to draw
1353    * @param offset vertical offset (used when called from wrapped alignment code)
1354    */
1355   private void drawUnwrappedSelection(Graphics2D g, SequenceGroup group,
1356           int startRes, int endRes, int startSeq, int endSeq, int offset)
1357   {
1358     int charWidth = av.getCharWidth();
1359           
1360     if (!av.hasHiddenColumns())
1361     {
1362       drawPartialGroupOutline(g, group, startRes, endRes, startSeq, endSeq,
1363               offset);
1364     }
1365     else
1366     {
1367       // package into blocks of visible columns
1368       int screenY = 0;
1369       int blockStart;
1370       int blockEnd;
1371
1372       HiddenColumns hidden = av.getAlignment().getHiddenColumns();
1373       VisibleContigsIterator regions = hidden
1374               .getVisContigsIterator(startRes, endRes + 1, true);
1375       while (regions.hasNext())
1376       {
1377         int[] region = regions.next();
1378         blockEnd = region[1];
1379         blockStart = region[0];
1380
1381         g.translate(screenY * charWidth, 0);
1382         drawPartialGroupOutline(g, group,
1383                 blockStart, blockEnd, startSeq, endSeq, offset);
1384
1385         g.translate(-screenY * charWidth, 0);
1386         screenY += blockEnd - blockStart + 1;
1387       }
1388     }
1389   }
1390
1391   /*
1392    * Draw the selection group as a separate image and overlay
1393    */
1394   private void drawPartialGroupOutline(Graphics2D g, SequenceGroup group,
1395           int startRes, int endRes, int startSeq, int endSeq,
1396           int verticalOffset)
1397   {
1398     int charHeight = av.getCharHeight();
1399     int charWidth = av.getCharWidth();
1400     int visWidth = (endRes - startRes + 1) * charWidth;
1401
1402     int oldY = -1;
1403     int i = 0;
1404     boolean inGroup = false;
1405     int top = -1;
1406     int bottom = -1;
1407     int sy = -1;
1408
1409     List<SequenceI> seqs = group.getSequences(null);
1410
1411     // position of start residue of group relative to startRes, in pixels
1412     int sx = (group.getStartRes() - startRes) * charWidth;
1413
1414     // width of group in pixels
1415     int xwidth = (((group.getEndRes() + 1) - group.getStartRes())
1416             * charWidth) - 1;
1417
1418     if (!(sx + xwidth < 0 || sx > visWidth))
1419     {
1420       for (i = startSeq; i <= endSeq; i++)
1421       {
1422         sy = verticalOffset + (i - startSeq) * charHeight;
1423
1424         if ((sx <= (endRes - startRes) * charWidth)
1425                 && seqs.contains(av.getAlignment().getSequenceAt(i)))
1426         {
1427           if ((bottom == -1)
1428                   && !seqs.contains(av.getAlignment().getSequenceAt(i + 1)))
1429           {
1430             bottom = sy + charHeight;
1431           }
1432
1433           if (!inGroup)
1434           {
1435             if (((top == -1) && (i == 0)) || !seqs
1436                     .contains(av.getAlignment().getSequenceAt(i - 1)))
1437             {
1438               top = sy;
1439             }
1440
1441             oldY = sy;
1442             inGroup = true;
1443           }
1444         }
1445         else if (inGroup)
1446         {
1447           drawVerticals(g, sx, xwidth, visWidth, oldY, sy);
1448           drawHorizontals(g, sx, xwidth, visWidth, top, bottom);
1449
1450           // reset top and bottom
1451           top = -1;
1452           bottom = -1;
1453           inGroup = false;
1454         }
1455       }
1456       if (inGroup)
1457       {
1458         sy = verticalOffset + ((i - startSeq) * charHeight);
1459         drawVerticals(g, sx, xwidth, visWidth, oldY, sy);
1460         drawHorizontals(g, sx, xwidth, visWidth, top, bottom);
1461       }
1462     }
1463   }
1464
1465   /**
1466    * Draw horizontal selection group boundaries at top and bottom positions
1467    * 
1468    * @param g
1469    *          graphics object to draw on
1470    * @param sx
1471    *          start x position
1472    * @param xwidth
1473    *          width of gap
1474    * @param visWidth
1475    *          visWidth maximum available width
1476    * @param top
1477    *          position to draw top of group at
1478    * @param bottom
1479    *          position to draw bottom of group at
1480    */
1481   private void drawHorizontals(Graphics2D g, int sx, int xwidth,
1482           int visWidth, int top, int bottom)
1483   {
1484     int width = xwidth;
1485     int startx = sx;
1486     if (startx < 0)
1487     {
1488       width += startx;
1489       startx = 0;
1490     }
1491
1492     // don't let width extend beyond current block, or group extent
1493     // fixes JAL-2672
1494     if (startx + width >= visWidth)
1495     {
1496       width = visWidth - startx;
1497     }
1498
1499     if (top != -1)
1500     {
1501       g.drawLine(startx, top, startx + width, top);
1502     }
1503
1504     if (bottom != -1)
1505     {
1506       g.drawLine(startx, bottom - 1, startx + width, bottom - 1);
1507     }
1508   }
1509
1510   /**
1511    * Draw vertical lines at sx and sx+xwidth providing they lie within
1512    * [0,visWidth)
1513    * 
1514    * @param g
1515    *          graphics object to draw on
1516    * @param sx
1517    *          start x position
1518    * @param xwidth
1519    *          width of gap
1520    * @param visWidth
1521    *          visWidth maximum available width
1522    * @param oldY
1523    *          top y value
1524    * @param sy
1525    *          bottom y value
1526    */
1527   private void drawVerticals(Graphics2D g, int sx, int xwidth, int visWidth,
1528           int oldY, int sy)
1529   {
1530     // if start position is visible, draw vertical line to left of
1531     // group
1532     if (sx >= 0 && sx < visWidth)
1533     {
1534       g.drawLine(sx, oldY, sx, sy);
1535     }
1536
1537     // if end position is visible, draw vertical line to right of
1538     // group
1539     if (sx + xwidth < visWidth)
1540     {
1541       g.drawLine(sx + xwidth, oldY, sx + xwidth, sy);
1542     }
1543   }
1544   
1545   /**
1546    * Highlights search results in the visible region by rendering as white text
1547    * on a black background. Any previous highlighting is removed. Answers true
1548    * if any highlight was left on the visible alignment (so status bar should be
1549    * set to match), else false.
1550    * <p>
1551    * Currently fastPaint is not implemented for wrapped alignments. If a wrapped
1552    * alignment had to be scrolled to show the highlighted region, then it should
1553    * be fully redrawn, otherwise a fast paint can be performed. This argument
1554    * could be removed if fast paint of scrolled wrapped alignment is coded in
1555    * future (JAL-2609).
1556    * 
1557    * @param results
1558    * @param noFastPaint
1559    * @return
1560    */
1561   public boolean highlightSearchResults(SearchResultsI results,
1562           boolean noFastPaint)
1563   {
1564     if (fastpainting)
1565     {
1566       return false;
1567     }
1568     boolean wrapped = av.getWrapAlignment();
1569     try
1570     {
1571       fastPaint = !noFastPaint;
1572       fastpainting = fastPaint;
1573
1574       /*
1575        * to avoid redrawing the whole visible region, we instead
1576        * redraw just the minimal regions to remove previous highlights
1577        * and add new ones
1578        */
1579       SearchResultsI previous = av.getSearchResults();
1580       av.setSearchResults(results);
1581       boolean redrawn = false;
1582       boolean drawn = false;
1583       if (wrapped)
1584       {
1585         redrawn = drawMappedPositionsWrapped(previous);
1586         drawn = drawMappedPositionsWrapped(results);
1587         redrawn |= drawn;
1588       }
1589       else
1590       {
1591         redrawn = drawMappedPositions(previous);
1592         drawn = drawMappedPositions(results);
1593         redrawn |= drawn;
1594       }
1595
1596       /*
1597        * if highlights were either removed or added, repaint
1598        */
1599       if (redrawn)
1600       {
1601         repaint();
1602       }
1603
1604       /*
1605        * return true only if highlights were added
1606        */
1607       return drawn;
1608
1609     } finally
1610     {
1611       fastpainting = false;
1612     }
1613   }
1614
1615   /**
1616    * Redraws the minimal rectangle in the visible region (if any) that includes
1617    * mapped positions of the given search results. Whether or not positions are
1618    * highlighted depends on the SearchResults set on the Viewport. This allows
1619    * this method to be called to either clear or set highlighting. Answers true
1620    * if any positions were drawn (in which case a repaint is still required),
1621    * else false.
1622    * 
1623    * @param results
1624    * @return
1625    */
1626   protected boolean drawMappedPositions(SearchResultsI results)
1627   {
1628     if ((results == null) || (gg == null)) // JAL-2784 check gg is not null
1629     {
1630       return false;
1631     }
1632
1633     /*
1634      * calculate the minimal rectangle to redraw that 
1635      * includes both new and existing search results
1636      */
1637     int firstSeq = Integer.MAX_VALUE;
1638     int lastSeq = -1;
1639     int firstCol = Integer.MAX_VALUE;
1640     int lastCol = -1;
1641     boolean matchFound = false;
1642
1643     ViewportRanges ranges = av.getRanges();
1644     int firstVisibleColumn = ranges.getStartRes();
1645     int lastVisibleColumn = ranges.getEndRes();
1646     AlignmentI alignment = av.getAlignment();
1647     if (av.hasHiddenColumns())
1648     {
1649       firstVisibleColumn = alignment.getHiddenColumns()
1650               .visibleToAbsoluteColumn(firstVisibleColumn);
1651       lastVisibleColumn = alignment.getHiddenColumns()
1652               .visibleToAbsoluteColumn(lastVisibleColumn);
1653     }
1654
1655     for (int seqNo = ranges.getStartSeq(); seqNo <= ranges
1656             .getEndSeq(); seqNo++)
1657     {
1658       SequenceI seq = alignment.getSequenceAt(seqNo);
1659
1660       int[] visibleResults = results.getResults(seq, firstVisibleColumn,
1661               lastVisibleColumn);
1662       if (visibleResults != null)
1663       {
1664         for (int i = 0; i < visibleResults.length - 1; i += 2)
1665         {
1666           int firstMatchedColumn = visibleResults[i];
1667           int lastMatchedColumn = visibleResults[i + 1];
1668           if (firstMatchedColumn <= lastVisibleColumn
1669                   && lastMatchedColumn >= firstVisibleColumn)
1670           {
1671             /*
1672              * found a search results match in the visible region - 
1673              * remember the first and last sequence matched, and the first
1674              * and last visible columns in the matched positions
1675              */
1676             matchFound = true;
1677             firstSeq = Math.min(firstSeq, seqNo);
1678             lastSeq = Math.max(lastSeq, seqNo);
1679             firstMatchedColumn = Math.max(firstMatchedColumn,
1680                     firstVisibleColumn);
1681             lastMatchedColumn = Math.min(lastMatchedColumn,
1682                     lastVisibleColumn);
1683             firstCol = Math.min(firstCol, firstMatchedColumn);
1684             lastCol = Math.max(lastCol, lastMatchedColumn);
1685           }
1686         }
1687       }
1688     }
1689
1690     if (matchFound)
1691     {
1692       if (av.hasHiddenColumns())
1693       {
1694         firstCol = alignment.getHiddenColumns()
1695                 .absoluteToVisibleColumn(firstCol);
1696         lastCol = alignment.getHiddenColumns().absoluteToVisibleColumn(lastCol);
1697       }
1698       int transX = (firstCol - ranges.getStartRes()) * av.getCharWidth();
1699       int transY = (firstSeq - ranges.getStartSeq()) * av.getCharHeight();
1700       gg.translate(transX, transY);
1701       drawPanel(gg, firstCol, lastCol, firstSeq, lastSeq, 0);
1702       gg.translate(-transX, -transY);
1703     }
1704
1705     return matchFound;
1706   }
1707
1708   @Override
1709   public void propertyChange(PropertyChangeEvent evt)
1710   {
1711     String eventName = evt.getPropertyName();
1712
1713     if (eventName.equals(SequenceGroup.SEQ_GROUP_CHANGED))
1714     {
1715       fastPaint = true;
1716       repaint();
1717       return;
1718     }
1719     else if (eventName.equals(ViewportRanges.MOVE_VIEWPORT))
1720     {
1721       fastPaint = false;
1722       repaint();
1723       return;
1724     }
1725
1726     int scrollX = 0;
1727     if (eventName.equals(ViewportRanges.STARTRES)
1728             || eventName.equals(ViewportRanges.STARTRESANDSEQ))
1729     {
1730       // Make sure we're not trying to draw a panel
1731       // larger than the visible window
1732       if (eventName.equals(ViewportRanges.STARTRES))
1733       {
1734         scrollX = (int) evt.getNewValue() - (int) evt.getOldValue();
1735       }
1736       else
1737       {
1738         scrollX = ((int[]) evt.getNewValue())[0]
1739                 - ((int[]) evt.getOldValue())[0];
1740       }
1741       ViewportRanges vpRanges = av.getRanges();
1742
1743       int range = vpRanges.getEndRes() - vpRanges.getStartRes() + 1;
1744       if (scrollX > range)
1745       {
1746         scrollX = range;
1747       }
1748       else if (scrollX < -range)
1749       {
1750         scrollX = -range;
1751       }
1752     }
1753       // Both scrolling and resizing change viewport ranges: scrolling changes
1754       // both start and end points, but resize only changes end values.
1755       // Here we only want to fastpaint on a scroll, with resize using a normal
1756       // paint, so scroll events are identified as changes to the horizontal or
1757       // vertical start value.
1758       if (eventName.equals(ViewportRanges.STARTRES))
1759       {
1760           if (av.getWrapAlignment())
1761           {
1762             fastPaintWrapped(scrollX);
1763           }
1764           else
1765           {
1766             fastPaint(scrollX, 0);
1767           }
1768       }
1769       else if (eventName.equals(ViewportRanges.STARTSEQ))
1770       {
1771         // scroll
1772         fastPaint(0, (int) evt.getNewValue() - (int) evt.getOldValue());
1773       }
1774       else if (eventName.equals(ViewportRanges.STARTRESANDSEQ))
1775       {
1776         if (av.getWrapAlignment())
1777         {
1778           fastPaintWrapped(scrollX);
1779         }
1780         else
1781         {
1782           fastPaint(scrollX, 0);
1783         }
1784     }
1785     else if (eventName.equals(ViewportRanges.STARTSEQ))
1786     {
1787       // scroll
1788       fastPaint(0, (int) evt.getNewValue() - (int) evt.getOldValue());
1789     }
1790     else if (eventName.equals(ViewportRanges.STARTRESANDSEQ))
1791     {
1792       if (av.getWrapAlignment())
1793       {
1794         fastPaintWrapped(scrollX);
1795       }
1796     }
1797   }
1798
1799   /**
1800    * Does a minimal update of the image for a scroll movement. This method
1801    * handles scroll movements of up to one width of the wrapped alignment (one
1802    * click in the vertical scrollbar). Larger movements (for example after a
1803    * scroll to highlight a mapped position) trigger a full redraw instead.
1804    * 
1805    * @param scrollX
1806    *          number of positions scrolled (right if positive, left if negative)
1807    */
1808   protected void fastPaintWrapped(int scrollX)
1809   {
1810     ViewportRanges ranges = av.getRanges();
1811
1812     if (Math.abs(scrollX) >= ranges.getViewportWidth())
1813     {
1814       /*
1815        * shift of one view width or more is 
1816        * overcomplicated to handle in this method
1817        */
1818       fastPaint = false;
1819       repaint();
1820       return;
1821     }
1822
1823     if (fastpainting || gg == null)
1824     {
1825       return;
1826     }
1827
1828     fastPaint = true;
1829     fastpainting = true;
1830
1831     try
1832     {
1833       calculateWrappedGeometry(getWidth(), getHeight());
1834
1835       /*
1836        * relocate the regions of the alignment that are still visible
1837        */
1838       shiftWrappedAlignment(-scrollX);
1839
1840       /*
1841        * add new columns (sequence, annotation)
1842        * - at top left if scrollX < 0 
1843        * - at right of last two widths if scrollX > 0
1844        */
1845       if (scrollX < 0)
1846       {
1847         int startRes = ranges.getStartRes();
1848         drawWrappedWidth(gg, wrappedSpaceAboveAlignment, startRes, startRes
1849                 - scrollX - 1, getHeight());
1850       }
1851       else
1852       {
1853         fastPaintWrappedAddRight(scrollX);
1854       }
1855
1856       /*
1857        * draw all scales (if  shown) and hidden column markers
1858        */
1859       drawWrappedDecorators(gg, ranges.getStartRes());
1860
1861       repaint();
1862     } finally
1863     {
1864       fastpainting = false;
1865     }
1866   }
1867
1868   /**
1869    * Draws the specified number of columns at the 'end' (bottom right) of a
1870    * wrapped alignment view, including sequences and annotations if shown, but
1871    * not scales. Also draws the same number of columns at the right hand end of
1872    * the second last width shown, if the last width is not full height (so
1873    * cannot simply be copied from the graphics image).
1874    * 
1875    * @param columns
1876    */
1877   protected void fastPaintWrappedAddRight(int columns)
1878   {
1879     if (columns == 0)
1880     {
1881       return;
1882     }
1883
1884     ViewportRanges ranges = av.getRanges();
1885     int viewportWidth = ranges.getViewportWidth();
1886     int charWidth = av.getCharWidth();
1887
1888     /**
1889      * draw full height alignment in the second last row, last columns, if the
1890      * last row was not full height
1891      */
1892     int visibleWidths = wrappedVisibleWidths;
1893     int canvasHeight = getHeight();
1894     boolean lastWidthPartHeight = (wrappedVisibleWidths * wrappedRepeatHeightPx) > canvasHeight;
1895
1896     if (lastWidthPartHeight)
1897     {
1898       int widthsAbove = Math.max(0, visibleWidths - 2);
1899       int ypos = wrappedRepeatHeightPx * widthsAbove
1900               + wrappedSpaceAboveAlignment;
1901       int endRes = ranges.getEndRes();
1902       endRes += widthsAbove * viewportWidth;
1903       int startRes = endRes - columns;
1904       int xOffset = ((startRes - ranges.getStartRes()) % viewportWidth)
1905               * charWidth;
1906
1907       /*
1908        * white fill first to erase annotations
1909        */
1910       gg.translate(xOffset, 0);
1911       gg.setColor(Color.white);
1912       gg.fillRect(labelWidthWest, ypos,
1913               (endRes - startRes + 1) * charWidth, wrappedRepeatHeightPx);
1914       gg.translate(-xOffset, 0);
1915
1916       drawWrappedWidth(gg, ypos, startRes, endRes, canvasHeight);
1917     }
1918
1919     /*
1920      * draw newly visible columns in last wrapped width (none if we
1921      * have reached the end of the alignment)
1922      * y-offset for drawing last width is height of widths above,
1923      * plus one gap row
1924      */
1925     int widthsAbove = visibleWidths - 1;
1926     int ypos = wrappedRepeatHeightPx * widthsAbove
1927             + wrappedSpaceAboveAlignment;
1928     int endRes = ranges.getEndRes();
1929     endRes += widthsAbove * viewportWidth;
1930     int startRes = endRes - columns + 1;
1931
1932     /*
1933      * white fill first to erase annotations
1934      */
1935     int xOffset = ((startRes - ranges.getStartRes()) % viewportWidth)
1936             * charWidth;
1937     gg.translate(xOffset, 0);
1938     gg.setColor(Color.white);
1939     int width = viewportWidth * charWidth - xOffset;
1940     gg.fillRect(labelWidthWest, ypos, width, wrappedRepeatHeightPx);
1941     gg.translate(-xOffset, 0);
1942
1943     gg.setFont(av.getFont());
1944     gg.setColor(Color.black);
1945
1946     if (startRes < ranges.getVisibleAlignmentWidth())
1947     {
1948       drawWrappedWidth(gg, ypos, startRes, endRes, canvasHeight);
1949     }
1950
1951     /*
1952      * and finally, white fill any space below the visible alignment
1953      */
1954     int heightBelow = canvasHeight - visibleWidths * wrappedRepeatHeightPx;
1955     if (heightBelow > 0)
1956     {
1957       gg.setColor(Color.white);
1958       gg.fillRect(0, canvasHeight - heightBelow, getWidth(), heightBelow);
1959     }
1960   }
1961
1962   /**
1963    * Shifts the visible alignment by the specified number of columns - left if
1964    * negative, right if positive. Copies and moves sequences and annotations (if
1965    * shown). Scales, hidden column markers and any newly visible columns must be
1966    * drawn separately.
1967    * 
1968    * @param positions
1969    */
1970   protected void shiftWrappedAlignment(int positions)
1971   {
1972     if (positions == 0)
1973     {
1974       return;
1975     }
1976     int charWidth = av.getCharWidth();
1977
1978     int canvasHeight = getHeight();
1979     ViewportRanges ranges = av.getRanges();
1980     int viewportWidth = ranges.getViewportWidth();
1981     int widthToCopy = (ranges.getViewportWidth() - Math.abs(positions))
1982             * charWidth;
1983     int heightToCopy = wrappedRepeatHeightPx - wrappedSpaceAboveAlignment;
1984     int xMax = ranges.getVisibleAlignmentWidth();
1985
1986     if (positions > 0)
1987     {
1988       /*
1989        * shift right (after scroll left)
1990        * for each wrapped width (starting with the last), copy (width-positions) 
1991        * columns from the left margin to the right margin, and copy positions 
1992        * columns from the right margin of the row above (if any) to the 
1993        * left margin of the current row
1994        */
1995
1996       /*
1997        * get y-offset of last wrapped width, first row of sequences
1998        */
1999       int y = canvasHeight / wrappedRepeatHeightPx * wrappedRepeatHeightPx;
2000       y += wrappedSpaceAboveAlignment;
2001       int copyFromLeftStart = labelWidthWest;
2002       int copyFromRightStart = copyFromLeftStart + widthToCopy;
2003
2004       while (y >= 0)
2005       {
2006         /*
2007          * shift 'widthToCopy' residues by 'positions' places to the right
2008          */
2009         gg.copyArea(copyFromLeftStart, y, widthToCopy, heightToCopy,
2010                 positions * charWidth, 0);
2011         if (y > 0)
2012         {
2013           /*
2014            * copy 'positions' residue from the row above (right hand end)
2015            * to this row's left hand end
2016            */
2017           gg.copyArea(copyFromRightStart, y - wrappedRepeatHeightPx,
2018                   positions * charWidth, heightToCopy, -widthToCopy,
2019                   wrappedRepeatHeightPx);
2020         }
2021
2022         y -= wrappedRepeatHeightPx;
2023       }
2024     }
2025     else
2026     {
2027       /*
2028        * shift left (after scroll right)
2029        * for each wrapped width (starting with the first), copy (width-positions) 
2030        * columns from the right margin to the left margin, and copy positions 
2031        * columns from the left margin of the row below (if any) to the 
2032        * right margin of the current row
2033        */
2034       int xpos = av.getRanges().getStartRes();
2035       int y = wrappedSpaceAboveAlignment;
2036       int copyFromRightStart = labelWidthWest - positions * charWidth;
2037
2038       while (y < canvasHeight)
2039       {
2040         gg.copyArea(copyFromRightStart, y, widthToCopy, heightToCopy,
2041                 positions * charWidth, 0);
2042         if (y + wrappedRepeatHeightPx < canvasHeight - wrappedRepeatHeightPx
2043                 && (xpos + viewportWidth <= xMax))
2044         {
2045           gg.copyArea(labelWidthWest, y + wrappedRepeatHeightPx, -positions
2046                   * charWidth, heightToCopy, widthToCopy,
2047                   -wrappedRepeatHeightPx);
2048         }
2049
2050         y += wrappedRepeatHeightPx;
2051         xpos += viewportWidth;
2052       }
2053     }
2054   }
2055
2056   
2057   /**
2058    * Redraws any positions in the search results in the visible region of a
2059    * wrapped alignment. Any highlights are drawn depending on the search results
2060    * set on the Viewport, not the <code>results</code> argument. This allows
2061    * this method to be called either to clear highlights (passing the previous
2062    * search results), or to draw new highlights.
2063    * 
2064    * @param results
2065    * @return
2066    */
2067   protected boolean drawMappedPositionsWrapped(SearchResultsI results)
2068   {
2069     if ((results == null) || (gg == null)) // JAL-2784 check gg is not null
2070     {
2071       return false;
2072     }
2073     int charHeight = av.getCharHeight();
2074
2075     boolean matchFound = false;
2076
2077     calculateWrappedGeometry(getWidth(), getHeight());
2078     int wrappedWidth = av.getWrappedWidth();
2079     int wrappedHeight = wrappedRepeatHeightPx;
2080
2081     ViewportRanges ranges = av.getRanges();
2082     int canvasHeight = getHeight();
2083     int repeats = canvasHeight / wrappedHeight;
2084     if (canvasHeight / wrappedHeight > 0)
2085     {
2086       repeats++;
2087     }
2088
2089     int firstVisibleColumn = ranges.getStartRes();
2090     int lastVisibleColumn = ranges.getStartRes() + repeats
2091             * ranges.getViewportWidth() - 1;
2092
2093     AlignmentI alignment = av.getAlignment();
2094     if (av.hasHiddenColumns())
2095     {
2096       firstVisibleColumn = alignment.getHiddenColumns()
2097               .visibleToAbsoluteColumn(firstVisibleColumn);
2098       lastVisibleColumn = alignment.getHiddenColumns()
2099               .visibleToAbsoluteColumn(lastVisibleColumn);
2100     }
2101
2102     int gapHeight = charHeight * (av.getScaleAboveWrapped() ? 2 : 1);
2103
2104     for (int seqNo = ranges.getStartSeq(); seqNo <= ranges
2105             .getEndSeq(); seqNo++)
2106     {
2107       SequenceI seq = alignment.getSequenceAt(seqNo);
2108
2109       int[] visibleResults = results.getResults(seq, firstVisibleColumn,
2110               lastVisibleColumn);
2111       if (visibleResults != null)
2112       {
2113         for (int i = 0; i < visibleResults.length - 1; i += 2)
2114         {
2115           int firstMatchedColumn = visibleResults[i];
2116           int lastMatchedColumn = visibleResults[i + 1];
2117           if (firstMatchedColumn <= lastVisibleColumn
2118                   && lastMatchedColumn >= firstVisibleColumn)
2119           {
2120             /*
2121              * found a search results match in the visible region
2122              */
2123             firstMatchedColumn = Math.max(firstMatchedColumn,
2124                     firstVisibleColumn);
2125             lastMatchedColumn = Math.min(lastMatchedColumn,
2126                     lastVisibleColumn);
2127
2128             /*
2129              * draw each mapped position separately (as contiguous positions may
2130              * wrap across lines)
2131              */
2132             for (int mappedPos = firstMatchedColumn; mappedPos <= lastMatchedColumn; mappedPos++)
2133             {
2134               int displayColumn = mappedPos;
2135               if (av.hasHiddenColumns())
2136               {
2137                 displayColumn = alignment.getHiddenColumns()
2138                         .absoluteToVisibleColumn(displayColumn);
2139               }
2140
2141               /*
2142                * transX: offset from left edge of canvas to residue position
2143                */
2144               int transX = labelWidthWest
2145                       + ((displayColumn - ranges.getStartRes()) % wrappedWidth)
2146                       * av.getCharWidth();
2147
2148               /*
2149                * transY: offset from top edge of canvas to residue position
2150                */
2151               int transY = gapHeight;
2152               transY += (displayColumn - ranges.getStartRes())
2153                       / wrappedWidth * wrappedHeight;
2154               transY += (seqNo - ranges.getStartSeq()) * av.getCharHeight();
2155
2156               /*
2157                * yOffset is from graphics origin to start of visible region
2158                */
2159               int yOffset = 0;// (displayColumn / wrappedWidth) * wrappedHeight;
2160               if (transY < getHeight())
2161               {
2162                 matchFound = true;
2163                 gg.translate(transX, transY);
2164                 drawPanel(gg, displayColumn, displayColumn, seqNo, seqNo,
2165                         yOffset);
2166                 gg.translate(-transX, -transY);
2167               }
2168             }
2169           }
2170         }
2171       }
2172     }
2173   
2174     return matchFound;
2175   }
2176
2177   /**
2178    * Answers the width in pixels of the left scale labels (0 if not shown)
2179    * 
2180    * @return
2181    */
2182   int getLabelWidthWest()
2183   {
2184     return labelWidthWest;
2185   }
2186 }