JAL-2609 fully erase scale above, tidy code change
[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.translate(labelWidthWest, 0);
842       g.setColor(Color.white);
843       g.fillRect(0, ypos - wrappedSpaceAboveAlignment, viewportWidth
844               * charWidth + labelWidthWest, wrappedSpaceAboveAlignment);
845       g.setColor(Color.black);
846       g.translate(-labelWidthWest, 0);
847
848       g.translate(labelWidthWest, 0);
849
850       if (av.getScaleAboveWrapped())
851       {
852         drawNorthScale(g, startCol, endColumn, ypos);
853       }
854
855       if (av.hasHiddenColumns() && av.getShowHiddenMarkers())
856       {
857         drawHiddenColumnMarkers(g, ypos, startCol, endColumn);
858       }
859
860       g.translate(-labelWidthWest, 0);
861
862       ypos += wrappedRepeatHeightPx;
863       startCol += viewportWidth;
864       widthsDrawn++;
865     }
866   }
867
868   /**
869    * Draws markers (triangles) above hidden column positions between startColumn
870    * and endColumn.
871    * 
872    * @param g
873    * @param ypos
874    * @param startColumn
875    * @param endColumn
876    */
877   protected void drawHiddenColumnMarkers(Graphics g, int ypos,
878           int startColumn, int endColumn)
879   {
880     int charHeight = av.getCharHeight();
881     int charWidth = av.getCharWidth();
882
883     g.setColor(Color.blue);
884     HiddenColumns hidden = av.getAlignment().getHiddenColumns();
885     List<Integer> positions = hidden.findHiddenRegionPositions();
886     for (int pos : positions)
887     {
888       int res = pos - startColumn;
889
890       if (res < 0 || res > endColumn - startColumn + 1)
891       {
892         continue;
893       }
894
895       /*
896        * draw a downward-pointing triangle at the hidden columns location
897        * (before the following visible column)
898        */
899       int xMiddle = res * charWidth;
900       int[] xPoints = new int[] { xMiddle - charHeight / 4,
901           xMiddle + charHeight / 4, xMiddle };
902       int yTop = ypos - (charHeight / 2);
903       int[] yPoints = new int[] { yTop, yTop, yTop + 8 };
904       g.fillPolygon(xPoints, yPoints, 3);
905     }
906   }
907
908   /*
909    * Draw a selection group over a wrapped alignment
910    */
911   private void drawWrappedSelection(Graphics2D g, SequenceGroup group,
912           int canvasWidth,
913           int canvasHeight, int startRes)
914   {
915         int charHeight = av.getCharHeight();
916         int charWidth = av.getCharWidth();
917           
918     // height gap above each panel
919     int hgap = charHeight;
920     if (av.getScaleAboveWrapped())
921     {
922       hgap += charHeight;
923     }
924
925     int cWidth = (canvasWidth - labelWidthEast - labelWidthWest)
926             / charWidth;
927     int cHeight = av.getAlignment().getHeight() * charHeight;
928
929     int startx = startRes;
930     int endx;
931     int ypos = hgap; // vertical offset
932     int maxwidth = av.getAlignment().getWidth();
933
934     if (av.hasHiddenColumns())
935     {
936       maxwidth = av.getAlignment().getHiddenColumns()
937               .findColumnPosition(maxwidth);
938     }
939
940     // chop the wrapped alignment extent up into panel-sized blocks and treat
941     // each block as if it were a block from an unwrapped alignment
942     while ((ypos <= canvasHeight) && (startx < maxwidth))
943     {
944       // set end value to be start + width, or maxwidth, whichever is smaller
945       endx = startx + cWidth - 1;
946
947       if (endx > maxwidth)
948       {
949         endx = maxwidth;
950       }
951
952       g.translate(labelWidthWest, 0);
953
954       drawUnwrappedSelection(g, group, startx, endx, 0,
955               av.getAlignment().getHeight() - 1,
956               ypos);
957
958       g.translate(-labelWidthWest, 0);
959
960       // update vertical offset
961       ypos += cHeight + getAnnotationHeight() + hgap;
962
963       // update horizontal offset
964       startx += cWidth;
965     }
966   }
967
968   int getAnnotationHeight()
969   {
970     if (!av.isShowAnnotation())
971     {
972       return 0;
973     }
974
975     if (annotations == null)
976     {
977       annotations = new AnnotationPanel(av);
978     }
979
980     return annotations.adjustPanelHeight();
981   }
982
983   /**
984    * Draws the visible region of the alignment on the graphics context. If there
985    * are hidden column markers in the visible region, then each sub-region
986    * between the markers is drawn separately, followed by the hidden column
987    * marker.
988    * 
989    * @param g1
990    *          the graphics context, positioned at the first residue to be drawn
991    * @param startRes
992    *          offset of the first column to draw (0..)
993    * @param endRes
994    *          offset of the last column to draw (0..)
995    * @param startSeq
996    *          offset of the first sequence to draw (0..)
997    * @param endSeq
998    *          offset of the last sequence to draw (0..)
999    * @param yOffset
1000    *          vertical offset at which to draw (for wrapped alignments)
1001    */
1002   public void drawPanel(Graphics g1, final int startRes, final int endRes,
1003           final int startSeq, final int endSeq, final int yOffset)
1004   {
1005     int charHeight = av.getCharHeight();
1006     int charWidth = av.getCharWidth();
1007
1008     if (!av.hasHiddenColumns())
1009     {
1010       draw(g1, startRes, endRes, startSeq, endSeq, yOffset);
1011     }
1012     else
1013     {
1014       int screenY = 0;
1015       final int screenYMax = endRes - startRes;
1016       int blockStart = startRes;
1017       int blockEnd = endRes;
1018
1019       for (int[] region : av.getAlignment().getHiddenColumns()
1020               .getHiddenColumnsCopy())
1021       {
1022         int hideStart = region[0];
1023         int hideEnd = region[1];
1024
1025         if (hideStart <= blockStart)
1026         {
1027           blockStart += (hideEnd - hideStart) + 1;
1028           continue;
1029         }
1030
1031         /*
1032          * draw up to just before the next hidden region, or the end of
1033          * the visible region, whichever comes first
1034          */
1035         blockEnd = Math.min(hideStart - 1, blockStart + screenYMax
1036                 - screenY);
1037
1038         g1.translate(screenY * charWidth, 0);
1039
1040         draw(g1, blockStart, blockEnd, startSeq, endSeq, yOffset);
1041
1042         /*
1043          * draw the downline of the hidden column marker (ScalePanel draws the
1044          * triangle on top) if we reached it
1045          */
1046         if (av.getShowHiddenMarkers() && blockEnd == hideStart - 1)
1047         {
1048           g1.setColor(Color.blue);
1049
1050           g1.drawLine((blockEnd - blockStart + 1) * charWidth - 1,
1051                   0 + yOffset, (blockEnd - blockStart + 1) * charWidth - 1,
1052                   (endSeq - startSeq + 1) * charHeight + yOffset);
1053         }
1054
1055         g1.translate(-screenY * charWidth, 0);
1056         screenY += blockEnd - blockStart + 1;
1057         blockStart = hideEnd + 1;
1058
1059         if (screenY > screenYMax)
1060         {
1061           // already rendered last block
1062           return;
1063         }
1064       }
1065
1066       if (screenY <= screenYMax)
1067       {
1068         // remaining visible region to render
1069         blockEnd = blockStart + screenYMax - screenY;
1070         g1.translate(screenY * charWidth, 0);
1071         draw(g1, blockStart, blockEnd, startSeq, endSeq, yOffset);
1072
1073         g1.translate(-screenY * charWidth, 0);
1074       }
1075     }
1076
1077   }
1078
1079   /**
1080    * Draws a region of the visible alignment
1081    * 
1082    * @param g1
1083    * @param startRes
1084    *          offset of the first column in the visible region (0..)
1085    * @param endRes
1086    *          offset of the last column in the visible region (0..)
1087    * @param startSeq
1088    *          offset of the first sequence in the visible region (0..)
1089    * @param endSeq
1090    *          offset of the last sequence in the visible region (0..)
1091    * @param yOffset
1092    *          vertical offset at which to draw (for wrapped alignments)
1093    */
1094   private void draw(Graphics g, int startRes, int endRes, int startSeq,
1095           int endSeq, int offset)
1096   {
1097     int charHeight = av.getCharHeight();
1098     int charWidth = av.getCharWidth();
1099
1100     g.setFont(av.getFont());
1101     seqRdr.prepare(g, av.isRenderGaps());
1102
1103     SequenceI nextSeq;
1104
1105     // / First draw the sequences
1106     // ///////////////////////////
1107     for (int i = startSeq; i <= endSeq; i++)
1108     {
1109       nextSeq = av.getAlignment().getSequenceAt(i);
1110       if (nextSeq == null)
1111       {
1112         // occasionally, a race condition occurs such that the alignment row is
1113         // empty
1114         continue;
1115       }
1116       seqRdr.drawSequence(nextSeq, av.getAlignment().findAllGroups(nextSeq),
1117               startRes, endRes, offset + ((i - startSeq) * charHeight));
1118
1119       if (av.isShowSequenceFeatures())
1120       {
1121         fr.drawSequence(g, nextSeq, startRes, endRes,
1122                 offset + ((i - startSeq) * charHeight), false);
1123       }
1124
1125       /*
1126        * highlight search Results once sequence has been drawn
1127        */
1128       if (av.hasSearchResults())
1129       {
1130         SearchResultsI searchResults = av.getSearchResults();
1131         int[] visibleResults = searchResults.getResults(nextSeq,
1132                 startRes, endRes);
1133         if (visibleResults != null)
1134         {
1135           for (int r = 0; r < visibleResults.length; r += 2)
1136           {
1137             seqRdr.drawHighlightedText(nextSeq, visibleResults[r],
1138                     visibleResults[r + 1], (visibleResults[r] - startRes)
1139                             * charWidth, offset
1140                             + ((i - startSeq) * charHeight));
1141           }
1142         }
1143       }
1144
1145       if (av.cursorMode && cursorY == i && cursorX >= startRes
1146               && cursorX <= endRes)
1147       {
1148         seqRdr.drawCursor(nextSeq, cursorX, (cursorX - startRes) * charWidth,
1149                 offset + ((i - startSeq) * charHeight));
1150       }
1151     }
1152
1153     if (av.getSelectionGroup() != null
1154             || av.getAlignment().getGroups().size() > 0)
1155     {
1156       drawGroupsBoundaries(g, startRes, endRes, startSeq, endSeq, offset);
1157     }
1158
1159   }
1160
1161   void drawGroupsBoundaries(Graphics g1, int startRes, int endRes,
1162           int startSeq, int endSeq, int offset)
1163   {
1164     Graphics2D g = (Graphics2D) g1;
1165     //
1166     // ///////////////////////////////////
1167     // Now outline any areas if necessary
1168     // ///////////////////////////////////
1169
1170     SequenceGroup group = null;
1171     int groupIndex = -1;
1172
1173     if (av.getAlignment().getGroups().size() > 0)
1174     {
1175       group = av.getAlignment().getGroups().get(0);
1176       groupIndex = 0;
1177     }
1178
1179     if (group != null)
1180     {
1181       g.setStroke(new BasicStroke());
1182       g.setColor(group.getOutlineColour());
1183       
1184       do
1185       {
1186         drawPartialGroupOutline(g, group, startRes, endRes, startSeq,
1187                 endSeq, offset);
1188
1189         groupIndex++;
1190
1191         g.setStroke(new BasicStroke());
1192
1193         if (groupIndex >= av.getAlignment().getGroups().size())
1194         {
1195           break;
1196         }
1197
1198         group = av.getAlignment().getGroups().get(groupIndex);
1199
1200       } while (groupIndex < av.getAlignment().getGroups().size());
1201
1202     }
1203
1204   }
1205
1206
1207   /*
1208    * Draw the selection group as a separate image and overlay
1209    */
1210   private BufferedImage drawSelectionGroup(int startRes, int endRes,
1211           int startSeq, int endSeq)
1212   {
1213     // get a new image of the correct size
1214     BufferedImage selectionImage = setupImage();
1215
1216     if (selectionImage == null)
1217     {
1218       return null;
1219     }
1220
1221     SequenceGroup group = av.getSelectionGroup();
1222     if (group == null)
1223     {
1224       // nothing to draw
1225       return null;
1226     }
1227
1228     // set up drawing colour
1229     Graphics2D g = (Graphics2D) selectionImage.getGraphics();
1230
1231     setupSelectionGroup(g, selectionImage);
1232
1233     if (!av.getWrapAlignment())
1234     {
1235       drawUnwrappedSelection(g, group, startRes, endRes, startSeq, endSeq,
1236               0);
1237     }
1238     else
1239     {
1240       drawWrappedSelection(g, group, getWidth(), getHeight(),
1241               av.getRanges().getStartRes());
1242     }
1243
1244     g.dispose();
1245     return selectionImage;
1246   }
1247
1248   /*
1249    * Set up graphics for selection group
1250    */
1251   private void setupSelectionGroup(Graphics2D g,
1252           BufferedImage selectionImage)
1253   {
1254     // set background to transparent
1255     g.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f));
1256     g.fillRect(0, 0, selectionImage.getWidth(), selectionImage.getHeight());
1257
1258     // set up foreground to draw red dashed line
1259     g.setComposite(AlphaComposite.Src);
1260     g.setStroke(new BasicStroke(1, BasicStroke.CAP_BUTT,
1261             BasicStroke.JOIN_ROUND, 3f, new float[]
1262     { 5f, 3f }, 0f));
1263     g.setColor(Color.RED);
1264   }
1265
1266   /*
1267    * Draw a selection group over an unwrapped alignment
1268    * @param g graphics object to draw with
1269    * @param group selection group
1270    * @param startRes start residue of area to draw
1271    * @param endRes end residue of area to draw
1272    * @param startSeq start sequence of area to draw
1273    * @param endSeq end sequence of area to draw
1274    * @param offset vertical offset (used when called from wrapped alignment code)
1275    */
1276   private void drawUnwrappedSelection(Graphics2D g, SequenceGroup group,
1277           int startRes, int endRes, int startSeq, int endSeq, int offset)
1278   {
1279         int charWidth = av.getCharWidth();
1280           
1281     if (!av.hasHiddenColumns())
1282     {
1283       drawPartialGroupOutline(g, group, startRes, endRes, startSeq, endSeq,
1284               offset);
1285     }
1286     else
1287     {
1288       // package into blocks of visible columns
1289       int screenY = 0;
1290       int blockStart = startRes;
1291       int blockEnd = endRes;
1292
1293       for (int[] region : av.getAlignment().getHiddenColumns()
1294               .getHiddenColumnsCopy())
1295       {
1296         int hideStart = region[0];
1297         int hideEnd = region[1];
1298
1299         if (hideStart <= blockStart)
1300         {
1301           blockStart += (hideEnd - hideStart) + 1;
1302           continue;
1303         }
1304
1305         blockEnd = hideStart - 1;
1306
1307         g.translate(screenY * charWidth, 0);
1308         drawPartialGroupOutline(g, group,
1309                 blockStart, blockEnd, startSeq, endSeq, offset);
1310
1311         g.translate(-screenY * charWidth, 0);
1312         screenY += blockEnd - blockStart + 1;
1313         blockStart = hideEnd + 1;
1314
1315         if (screenY > (endRes - startRes))
1316         {
1317           // already rendered last block
1318           break;
1319         }
1320       }
1321
1322       if (screenY <= (endRes - startRes))
1323       {
1324         // remaining visible region to render
1325         blockEnd = blockStart + (endRes - startRes) - screenY;
1326         g.translate(screenY * charWidth, 0);
1327         drawPartialGroupOutline(g, group,
1328                 blockStart, blockEnd, startSeq, endSeq, offset);
1329         
1330         g.translate(-screenY * charWidth, 0);
1331       }
1332     }
1333   }
1334
1335   /*
1336    * Draw the selection group as a separate image and overlay
1337    */
1338   private void drawPartialGroupOutline(Graphics2D g, SequenceGroup group,
1339           int startRes, int endRes, int startSeq, int endSeq,
1340           int verticalOffset)
1341   {
1342         int charHeight = av.getCharHeight();
1343         int charWidth = av.getCharWidth();
1344           
1345     int visWidth = (endRes - startRes + 1) * charWidth;
1346
1347     int oldY = -1;
1348     int i = 0;
1349     boolean inGroup = false;
1350     int top = -1;
1351     int bottom = -1;
1352
1353     int sx = -1;
1354     int sy = -1;
1355     int xwidth = -1;
1356
1357     for (i = startSeq; i <= endSeq; i++)
1358     {
1359       // position of start residue of group relative to startRes, in pixels
1360       sx = (group.getStartRes() - startRes) * charWidth;
1361
1362       // width of group in pixels
1363       xwidth = (((group.getEndRes() + 1) - group.getStartRes()) * charWidth)
1364               - 1;
1365
1366       sy = verticalOffset + (i - startSeq) * charHeight;
1367
1368       if (sx + xwidth < 0 || sx > visWidth)
1369       {
1370         continue;
1371       }
1372
1373       if ((sx <= (endRes - startRes) * charWidth)
1374               && group.getSequences(null)
1375                       .contains(av.getAlignment().getSequenceAt(i)))
1376       {
1377         if ((bottom == -1) && !group.getSequences(null)
1378                 .contains(av.getAlignment().getSequenceAt(i + 1)))
1379         {
1380           bottom = sy + charHeight;
1381         }
1382
1383         if (!inGroup)
1384         {
1385           if (((top == -1) && (i == 0)) || !group.getSequences(null)
1386                   .contains(av.getAlignment().getSequenceAt(i - 1)))
1387           {
1388             top = sy;
1389           }
1390
1391           oldY = sy;
1392           inGroup = true;
1393         }
1394       }
1395       else
1396       {
1397         if (inGroup)
1398         {
1399           // if start position is visible, draw vertical line to left of
1400           // group
1401           if (sx >= 0 && sx < visWidth)
1402           {
1403             g.drawLine(sx, oldY, sx, sy);
1404           }
1405
1406           // if end position is visible, draw vertical line to right of
1407           // group
1408           if (sx + xwidth < visWidth)
1409           {
1410             g.drawLine(sx + xwidth, oldY, sx + xwidth, sy);
1411           }
1412
1413           if (sx < 0)
1414           {
1415             xwidth += sx;
1416             sx = 0;
1417           }
1418
1419           // don't let width extend beyond current block, or group extent
1420           // fixes JAL-2672
1421           if (sx + xwidth >= (endRes - startRes + 1) * charWidth)
1422           {
1423             xwidth = (endRes - startRes + 1) * charWidth - sx;
1424           }
1425           
1426           // draw horizontal line at top of group
1427           if (top != -1)
1428           {
1429             g.drawLine(sx, top, sx + xwidth, top);
1430             top = -1;
1431           }
1432
1433           // draw horizontal line at bottom of group
1434           if (bottom != -1)
1435           {
1436             g.drawLine(sx, bottom, sx + xwidth, bottom);
1437             bottom = -1;
1438           }
1439
1440           inGroup = false;
1441         }
1442       }
1443     }
1444
1445     if (inGroup)
1446     {
1447       sy = verticalOffset + ((i - startSeq) * charHeight);
1448       if (sx >= 0 && sx < visWidth)
1449       {
1450         g.drawLine(sx, oldY, sx, sy);
1451       }
1452
1453       if (sx + xwidth < visWidth)
1454       {
1455         g.drawLine(sx + xwidth, oldY, sx + xwidth, sy);
1456       }
1457
1458       if (sx < 0)
1459       {
1460         xwidth += sx;
1461         sx = 0;
1462       }
1463
1464       if (sx + xwidth > visWidth)
1465       {
1466         xwidth = visWidth;
1467       }
1468       else if (sx + xwidth >= (endRes - startRes + 1) * charWidth)
1469       {
1470         xwidth = (endRes - startRes + 1) * charWidth;
1471       }
1472
1473       if (top != -1)
1474       {
1475         g.drawLine(sx, top, sx + xwidth, top);
1476         top = -1;
1477       }
1478
1479       if (bottom != -1)
1480       {
1481         g.drawLine(sx, bottom - 1, sx + xwidth, bottom - 1);
1482         bottom = -1;
1483       }
1484
1485       inGroup = false;
1486     }
1487   }
1488   
1489   /**
1490    * Highlights search results in the visible region by rendering as white text
1491    * on a black background. Any previous highlighting is removed. Answers true
1492    * if any highlight was left on the visible alignment (so status bar should be
1493    * set to match), else false.
1494    * <p>
1495    * Currently fastPaint is not implemented for wrapped alignments. If a wrapped
1496    * alignment had to be scrolled to show the highlighted region, then it should
1497    * be fully redrawn, otherwise a fast paint can be performed. This argument
1498    * could be removed if fast paint of scrolled wrapped alignment is coded in
1499    * future (JAL-2609).
1500    * 
1501    * @param results
1502    * @param noFastPaint
1503    * @return
1504    */
1505   public boolean highlightSearchResults(SearchResultsI results,
1506           boolean noFastPaint)
1507   {
1508     if (fastpainting)
1509     {
1510       return false;
1511     }
1512     boolean wrapped = av.getWrapAlignment();
1513     try
1514     {
1515       fastPaint = !noFastPaint;
1516       fastpainting = fastPaint;
1517
1518       /*
1519        * to avoid redrawing the whole visible region, we instead
1520        * redraw just the minimal regions to remove previous highlights
1521        * and add new ones
1522        */
1523       SearchResultsI previous = av.getSearchResults();
1524       av.setSearchResults(results);
1525       boolean redrawn = false;
1526       boolean drawn = false;
1527       if (wrapped)
1528       {
1529         redrawn = drawMappedPositionsWrapped(previous);
1530         drawn = drawMappedPositionsWrapped(results);
1531         redrawn |= drawn;
1532       }
1533       else
1534       {
1535         redrawn = drawMappedPositions(previous);
1536         drawn = drawMappedPositions(results);
1537         redrawn |= drawn;
1538       }
1539
1540       /*
1541        * if highlights were either removed or added, repaint
1542        */
1543       if (redrawn)
1544       {
1545         repaint();
1546       }
1547
1548       /*
1549        * return true only if highlights were added
1550        */
1551       return drawn;
1552
1553     } finally
1554     {
1555       fastpainting = false;
1556     }
1557   }
1558
1559   /**
1560    * Redraws the minimal rectangle in the visible region (if any) that includes
1561    * mapped positions of the given search results. Whether or not positions are
1562    * highlighted depends on the SearchResults set on the Viewport. This allows
1563    * this method to be called to either clear or set highlighting. Answers true
1564    * if any positions were drawn (in which case a repaint is still required),
1565    * else false.
1566    * 
1567    * @param results
1568    * @return
1569    */
1570   protected boolean drawMappedPositions(SearchResultsI results)
1571   {
1572     if (results == null)
1573     {
1574       return false;
1575     }
1576
1577     /*
1578      * calculate the minimal rectangle to redraw that 
1579      * includes both new and existing search results
1580      */
1581     int firstSeq = Integer.MAX_VALUE;
1582     int lastSeq = -1;
1583     int firstCol = Integer.MAX_VALUE;
1584     int lastCol = -1;
1585     boolean matchFound = false;
1586
1587     ViewportRanges ranges = av.getRanges();
1588     int firstVisibleColumn = ranges.getStartRes();
1589     int lastVisibleColumn = ranges.getEndRes();
1590     AlignmentI alignment = av.getAlignment();
1591     if (av.hasHiddenColumns())
1592     {
1593       firstVisibleColumn = alignment.getHiddenColumns()
1594               .adjustForHiddenColumns(firstVisibleColumn);
1595       lastVisibleColumn = alignment.getHiddenColumns()
1596               .adjustForHiddenColumns(lastVisibleColumn);
1597     }
1598
1599     for (int seqNo = ranges.getStartSeq(); seqNo <= ranges
1600             .getEndSeq(); seqNo++)
1601     {
1602       SequenceI seq = alignment.getSequenceAt(seqNo);
1603
1604       int[] visibleResults = results.getResults(seq, firstVisibleColumn,
1605               lastVisibleColumn);
1606       if (visibleResults != null)
1607       {
1608         for (int i = 0; i < visibleResults.length - 1; i += 2)
1609         {
1610           int firstMatchedColumn = visibleResults[i];
1611           int lastMatchedColumn = visibleResults[i + 1];
1612           if (firstMatchedColumn <= lastVisibleColumn
1613                   && lastMatchedColumn >= firstVisibleColumn)
1614           {
1615             /*
1616              * found a search results match in the visible region - 
1617              * remember the first and last sequence matched, and the first
1618              * and last visible columns in the matched positions
1619              */
1620             matchFound = true;
1621             firstSeq = Math.min(firstSeq, seqNo);
1622             lastSeq = Math.max(lastSeq, seqNo);
1623             firstMatchedColumn = Math.max(firstMatchedColumn,
1624                     firstVisibleColumn);
1625             lastMatchedColumn = Math.min(lastMatchedColumn,
1626                     lastVisibleColumn);
1627             firstCol = Math.min(firstCol, firstMatchedColumn);
1628             lastCol = Math.max(lastCol, lastMatchedColumn);
1629           }
1630         }
1631       }
1632     }
1633
1634     if (matchFound)
1635     {
1636       if (av.hasHiddenColumns())
1637       {
1638         firstCol = alignment.getHiddenColumns()
1639                 .findColumnPosition(firstCol);
1640         lastCol = alignment.getHiddenColumns().findColumnPosition(lastCol);
1641       }
1642       int transX = (firstCol - ranges.getStartRes()) * av.getCharWidth();
1643       int transY = (firstSeq - ranges.getStartSeq()) * av.getCharHeight();
1644       gg.translate(transX, transY);
1645       drawPanel(gg, firstCol, lastCol, firstSeq, lastSeq, 0);
1646       gg.translate(-transX, -transY);
1647     }
1648
1649     return matchFound;
1650   }
1651
1652   @Override
1653   public void propertyChange(PropertyChangeEvent evt)
1654   {
1655     String eventName = evt.getPropertyName();
1656
1657     if (eventName.equals(SequenceGroup.SEQ_GROUP_CHANGED))
1658     {
1659       fastPaint = true;
1660       repaint();
1661     }
1662     else if (eventName.equals(ViewportRanges.STARTRES))
1663     {
1664       int scrollX = 0;
1665       if (eventName.equals(ViewportRanges.STARTRES))
1666       {
1667         // Make sure we're not trying to draw a panel
1668         // larger than the visible window
1669         ViewportRanges vpRanges = av.getRanges();
1670         scrollX = (int) evt.getNewValue() - (int) evt.getOldValue();
1671         int range = vpRanges.getViewportWidth();
1672         if (scrollX > range)
1673         {
1674           scrollX = range;
1675         }
1676         else if (scrollX < -range)
1677         {
1678           scrollX = -range;
1679         }
1680
1681         // Both scrolling and resizing change viewport ranges: scrolling changes
1682         // both start and end points, but resize only changes end values.
1683         // Here we only want to fastpaint on a scroll, with resize using a normal
1684         // paint, so scroll events are identified as changes to the horizontal or
1685         // vertical start value.
1686         
1687         // scroll - startres and endres both change
1688           if (av.getWrapAlignment())
1689         {
1690           fastPaintWrapped(scrollX);
1691         }
1692         else
1693         {
1694           fastPaint(scrollX, 0);
1695         }
1696       }
1697       else if (eventName.equals(ViewportRanges.STARTSEQ))
1698       {
1699         // scroll
1700         fastPaint(0, (int) evt.getNewValue() - (int) evt.getOldValue());
1701       }
1702     }
1703   }
1704
1705   /**
1706    * Does a minimal update of the image for a scroll movement. This method
1707    * handles scroll movements of up to one width of the wrapped alignment (one
1708    * click in the vertical scrollbar). Larger movements (for example after a
1709    * scroll to highlight a mapped position) trigger a full redraw instead.
1710    * 
1711    * @param scrollX
1712    *          number of positions scrolled (right if positive, left if negative)
1713    */
1714   protected void fastPaintWrapped(int scrollX)
1715   {
1716     ViewportRanges ranges = av.getRanges();
1717
1718     if (Math.abs(scrollX) > ranges.getViewportWidth())
1719     {
1720       /*
1721        * shift of more than one view width is 
1722        * overcomplicated to handle in this method
1723        */
1724       fastPaint = false;
1725       repaint();
1726       return;
1727     }
1728
1729     if (fastpainting || gg == null)
1730     {
1731       return;
1732     }
1733
1734     fastPaint = true;
1735     fastpainting = true;
1736
1737     try
1738     {
1739       calculateWrappedGeometry(getWidth(), getHeight());
1740
1741       /*
1742        * relocate the regions of the alignment that are still visible
1743        */
1744       shiftWrappedAlignment(-scrollX);
1745
1746       /*
1747        * add new columns (sequence, annotation)
1748        * - at top left if scrollX < 0 
1749        * - at right of last two widths if scrollX > 0
1750        */
1751       if (scrollX < 0)
1752       {
1753         int startRes = ranges.getStartRes();
1754         drawWrappedWidth(gg, wrappedSpaceAboveAlignment, startRes, startRes
1755                 - scrollX - 1, getHeight());
1756       }
1757       else
1758       {
1759         fastPaintWrappedAddRight(scrollX);
1760       }
1761
1762       /*
1763        * draw all scales (if  shown) and hidden column markers
1764        */
1765       drawWrappedDecorators(gg, ranges.getStartRes());
1766
1767       repaint();
1768     } finally
1769     {
1770       fastpainting = false;
1771     }
1772   }
1773
1774   /**
1775    * Draws the specified number of columns at the 'end' (bottom right) of a
1776    * wrapped alignment view, including sequences and annotations if shown, but
1777    * not scales. Also draws the same number of columns at the right hand end of
1778    * the second last width shown, if the last width is not full height (so
1779    * cannot simply be copied from the graphics image).
1780    * 
1781    * @param columns
1782    */
1783   protected void fastPaintWrappedAddRight(int columns)
1784   {
1785     if (columns == 0)
1786     {
1787       return;
1788     }
1789
1790     ViewportRanges ranges = av.getRanges();
1791     int viewportWidth = ranges.getViewportWidth();
1792     int charWidth = av.getCharWidth();
1793
1794     /**
1795      * draw full height alignment in the second last row, last columns, if the
1796      * last row was not full height
1797      */
1798     int visibleWidths = wrappedVisibleWidths;
1799     int canvasHeight = getHeight();
1800     boolean lastWidthPartHeight = (wrappedVisibleWidths * wrappedRepeatHeightPx) > canvasHeight;
1801
1802     if (lastWidthPartHeight)
1803     {
1804       int widthsAbove = Math.max(0, visibleWidths - 2);
1805       int ypos = wrappedRepeatHeightPx * widthsAbove
1806               + wrappedSpaceAboveAlignment;
1807       int endRes = ranges.getEndRes();
1808       endRes += widthsAbove * viewportWidth;
1809       int startRes = endRes - columns;
1810       int xOffset = ((startRes - ranges.getStartRes()) % viewportWidth)
1811               * charWidth;
1812
1813       /*
1814        * white fill first to erase annotations
1815        */
1816       gg.translate(xOffset, 0);
1817       gg.setColor(Color.white);
1818       gg.fillRect(labelWidthWest, ypos,
1819               (endRes - startRes + 1) * charWidth, wrappedRepeatHeightPx);
1820       gg.translate(-xOffset, 0);
1821
1822       drawWrappedWidth(gg, ypos, startRes, endRes, canvasHeight);
1823     }
1824
1825     /*
1826      * draw newly visible columns in last wrapped width (none if we
1827      * have reached the end of the alignment)
1828      * y-offset for drawing last width is height of widths above,
1829      * plus one gap row
1830      */
1831     int widthsAbove = visibleWidths - 1;
1832     int ypos = wrappedRepeatHeightPx * widthsAbove
1833             + wrappedSpaceAboveAlignment;
1834     int endRes = ranges.getEndRes();
1835     endRes += widthsAbove * viewportWidth;
1836     int startRes = endRes - columns + 1;
1837
1838     /*
1839      * white fill first to erase annotations
1840      */
1841     int xOffset = ((startRes - ranges.getStartRes()) % viewportWidth)
1842             * charWidth;
1843     gg.translate(xOffset, 0);
1844     gg.setColor(Color.white);
1845     int width = viewportWidth * charWidth - xOffset;
1846     gg.fillRect(labelWidthWest, ypos, width, wrappedRepeatHeightPx);
1847     gg.translate(-xOffset, 0);
1848
1849     gg.setFont(av.getFont());
1850     gg.setColor(Color.black);
1851
1852     if (startRes < ranges.getVisibleAlignmentWidth())
1853     {
1854       drawWrappedWidth(gg, ypos, startRes, endRes, canvasHeight);
1855     }
1856
1857     /*
1858      * and finally, white fill any space below the visible alignment
1859      */
1860     int heightBelow = canvasHeight - visibleWidths * wrappedRepeatHeightPx;
1861     if (heightBelow > 0)
1862     {
1863       gg.setColor(Color.white);
1864       gg.fillRect(0, canvasHeight - heightBelow, getWidth(), heightBelow);
1865     }
1866   }
1867
1868   /**
1869    * Shifts the visible alignment by the specified number of columns - left if
1870    * negative, right if positive. Copies and moves sequences and annotations (if
1871    * shown). Scales, hidden column markers and any newly visible columns must be
1872    * drawn separately.
1873    * 
1874    * @param positions
1875    */
1876   protected void shiftWrappedAlignment(int positions)
1877   {
1878     if (positions == 0)
1879     {
1880       return;
1881     }
1882     int charWidth = av.getCharWidth();
1883
1884     int canvasHeight = getHeight();
1885     ViewportRanges ranges = av.getRanges();
1886     int viewportWidth = ranges.getViewportWidth();
1887     int widthToCopy = (ranges.getViewportWidth() - Math.abs(positions))
1888             * charWidth;
1889     int heightToCopy = wrappedRepeatHeightPx - wrappedSpaceAboveAlignment;
1890     int xMax = ranges.getVisibleAlignmentWidth();
1891
1892     if (positions > 0)
1893     {
1894       /*
1895        * shift right (after scroll left)
1896        * for each wrapped width (starting with the last), copy (width-positions) 
1897        * columns from the left margin to the right margin, and copy positions 
1898        * columns from the right margin of the row above (if any) to the 
1899        * left margin of the current row
1900        */
1901
1902       /*
1903        * get y-offset of last wrapped width, first row of sequences
1904        */
1905       int y = canvasHeight / wrappedRepeatHeightPx * wrappedRepeatHeightPx;
1906       y += wrappedSpaceAboveAlignment;
1907       int copyFromLeftStart = labelWidthWest;
1908       int copyFromRightStart = copyFromLeftStart + widthToCopy;
1909
1910       while (y >= 0)
1911       {
1912         gg.copyArea(copyFromLeftStart, y, widthToCopy, heightToCopy,
1913                 positions * charWidth, 0);
1914         if (y > 0)
1915         {
1916           gg.copyArea(copyFromRightStart, y - wrappedRepeatHeightPx,
1917                   positions * charWidth, heightToCopy, -widthToCopy,
1918                   wrappedRepeatHeightPx);
1919         }
1920
1921         y -= wrappedRepeatHeightPx;
1922       }
1923     }
1924     else
1925     {
1926       /*
1927        * shift left (after scroll right)
1928        * for each wrapped width (starting with the first), copy (width-positions) 
1929        * columns from the right margin to the left margin, and copy positions 
1930        * columns from the left margin of the row below (if any) to the 
1931        * right margin of the current row
1932        */
1933       int xpos = av.getRanges().getStartRes();
1934       int y = wrappedSpaceAboveAlignment;
1935       int copyFromRightStart = labelWidthWest - positions * charWidth;
1936
1937       while (y < canvasHeight)
1938       {
1939         gg.copyArea(copyFromRightStart, y, widthToCopy, heightToCopy,
1940                 positions * charWidth, 0);
1941         if (y + wrappedRepeatHeightPx < canvasHeight - wrappedRepeatHeightPx
1942                 && (xpos + viewportWidth <= xMax))
1943         {
1944           gg.copyArea(labelWidthWest, y + wrappedRepeatHeightPx, -positions
1945                   * charWidth, heightToCopy, widthToCopy,
1946                   -wrappedRepeatHeightPx);
1947         }
1948
1949         y += wrappedRepeatHeightPx;
1950         xpos += viewportWidth;
1951       }
1952     }
1953   }
1954
1955   
1956   /**
1957    * Redraws any positions in the search results in the visible region of a
1958    * wrapped alignment. Any highlights are drawn depending on the search results
1959    * set on the Viewport, not the <code>results</code> argument. This allows
1960    * this method to be called either to clear highlights (passing the previous
1961    * search results), or to draw new highlights.
1962    * 
1963    * @param results
1964    * @return
1965    */
1966   protected boolean drawMappedPositionsWrapped(SearchResultsI results)
1967   {
1968     if (results == null)
1969     {
1970       return false;
1971     }
1972     int charHeight = av.getCharHeight();
1973
1974     boolean matchFound = false;
1975
1976     calculateWrappedGeometry(getWidth(), getHeight());
1977     int wrappedWidth = av.getWrappedWidth();
1978     int wrappedHeight = wrappedRepeatHeightPx;
1979
1980     ViewportRanges ranges = av.getRanges();
1981     int canvasHeight = getHeight();
1982     int repeats = canvasHeight / wrappedHeight;
1983     if (canvasHeight / wrappedHeight > 0)
1984     {
1985       repeats++;
1986     }
1987
1988     int firstVisibleColumn = ranges.getStartRes();
1989     int lastVisibleColumn = ranges.getStartRes() + repeats
1990             * ranges.getViewportWidth() - 1;
1991
1992     AlignmentI alignment = av.getAlignment();
1993     if (av.hasHiddenColumns())
1994     {
1995       firstVisibleColumn = alignment.getHiddenColumns()
1996               .adjustForHiddenColumns(firstVisibleColumn);
1997       lastVisibleColumn = alignment.getHiddenColumns()
1998               .adjustForHiddenColumns(lastVisibleColumn);
1999     }
2000
2001     int gapHeight = charHeight * (av.getScaleAboveWrapped() ? 2 : 1);
2002
2003     for (int seqNo = ranges.getStartSeq(); seqNo <= ranges
2004             .getEndSeq(); seqNo++)
2005     {
2006       SequenceI seq = alignment.getSequenceAt(seqNo);
2007
2008       int[] visibleResults = results.getResults(seq, firstVisibleColumn,
2009               lastVisibleColumn);
2010       if (visibleResults != null)
2011       {
2012         for (int i = 0; i < visibleResults.length - 1; i += 2)
2013         {
2014           int firstMatchedColumn = visibleResults[i];
2015           int lastMatchedColumn = visibleResults[i + 1];
2016           if (firstMatchedColumn <= lastVisibleColumn
2017                   && lastMatchedColumn >= firstVisibleColumn)
2018           {
2019             /*
2020              * found a search results match in the visible region
2021              */
2022             firstMatchedColumn = Math.max(firstMatchedColumn,
2023                     firstVisibleColumn);
2024             lastMatchedColumn = Math.min(lastMatchedColumn,
2025                     lastVisibleColumn);
2026
2027             /*
2028              * draw each mapped position separately (as contiguous positions may
2029              * wrap across lines)
2030              */
2031             for (int mappedPos = firstMatchedColumn; mappedPos <= lastMatchedColumn; mappedPos++)
2032             {
2033               int displayColumn = mappedPos;
2034               if (av.hasHiddenColumns())
2035               {
2036                 displayColumn = alignment.getHiddenColumns()
2037                         .findColumnPosition(displayColumn);
2038               }
2039
2040               /*
2041                * transX: offset from left edge of canvas to residue position
2042                */
2043               int transX = labelWidthWest
2044                       + ((displayColumn - ranges.getStartRes()) % wrappedWidth)
2045                       * av.getCharWidth();
2046
2047               /*
2048                * transY: offset from top edge of canvas to residue position
2049                */
2050               int transY = gapHeight;
2051               transY += (displayColumn - ranges.getStartRes())
2052                       / wrappedWidth * wrappedHeight;
2053               transY += (seqNo - ranges.getStartSeq()) * av.getCharHeight();
2054
2055               /*
2056                * yOffset is from graphics origin to start of visible region
2057                */
2058               int yOffset = 0;// (displayColumn / wrappedWidth) * wrappedHeight;
2059               if (transY < getHeight())
2060               {
2061                 matchFound = true;
2062                 gg.translate(transX, transY);
2063                 drawPanel(gg, displayColumn, displayColumn, seqNo, seqNo,
2064                         yOffset);
2065                 gg.translate(-transX, -transY);
2066               }
2067             }
2068           }
2069         }
2070       }
2071     }
2072   
2073     return matchFound;
2074   }
2075
2076   /**
2077    * Answers the width in pixels of the left scale labels (0 if not shown)
2078    * 
2079    * @return
2080    */
2081   int getLabelWidthWest()
2082   {
2083     return labelWidthWest;
2084   }
2085 }