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