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