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