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