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