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