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