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