JAL-2609 revised design (always draw all scales, fast paint relocates
[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, canvasHeight, 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 the wrapped alignment
677    * 
678    * @param g
679    * @param ypos
680    * @param startColumn
681    * @param endColumn
682    */
683   protected void drawWrappedDecorators(Graphics g, int canvasHeight,
684           int startColumn)
685   {
686     g.setFont(av.getFont());
687     g.setColor(Color.black);
688
689     int ypos = wrappedSpaceAboveAlignment;
690     ViewportRanges ranges = av.getRanges();
691     int viewportWidth = ranges.getViewportWidth();
692     int maxWidth = ranges.getVisibleAlignmentWidth();
693     int widthsDrawn = 0;
694     while (widthsDrawn < wrappedVisibleWidths)
695     {
696       int endColumn = Math.min(maxWidth, startColumn + viewportWidth - 1);
697
698       if (av.getScaleLeftWrapped())
699       {
700         drawVerticalScale(g, startColumn, endColumn - 1, ypos, true);
701       }
702
703       if (av.getScaleRightWrapped())
704       {
705         drawVerticalScale(g, startColumn, endColumn, ypos, false);
706       }
707
708       g.translate(labelWidthWest, 0);
709
710       if (av.getScaleAboveWrapped())
711       {
712         drawNorthScale(g, startColumn, endColumn, ypos);
713       }
714
715       if (av.hasHiddenColumns() && av.getShowHiddenMarkers())
716       {
717         drawHiddenColumnMarkers(g, ypos, startColumn, endColumn);
718       }
719
720       g.translate(-labelWidthWest, 0);
721
722       ypos += wrappedRepeatHeightPx;
723       startColumn += viewportWidth;
724       widthsDrawn++;
725     }
726   }
727
728   /**
729    * @param g
730    * @param ypos
731    * @param startColumn
732    * @param endColumn
733    */
734   protected void drawHiddenColumnMarkers(Graphics g, int ypos,
735           int startColumn, int endColumn)
736   {
737     g.setColor(Color.blue);
738     HiddenColumns hidden = av.getAlignment().getHiddenColumns();
739     List<Integer> positions = hidden.findHiddenRegionPositions();
740     for (int pos : positions)
741     {
742       int res = pos - startColumn;
743
744       if (res < 0 || res > endColumn - startColumn)
745       {
746         continue;
747       }
748
749       /*
750        * draw a downward-pointing triangle at the hidden columns location
751        * (before the following visible column)
752        */
753       int xMiddle = res * charWidth;
754       int[] xPoints = new int[] { xMiddle - charHeight / 4,
755           xMiddle + charHeight / 4, xMiddle };
756       int yTop = ypos - (charHeight / 2);
757       int[] yPoints = new int[] { yTop, yTop, yTop + 8 };
758       gg.fillPolygon(xPoints, yPoints, 3);
759     }
760   }
761
762   int getAnnotationHeight()
763   {
764     if (!av.isShowAnnotation())
765     {
766       return 0;
767     }
768
769     if (annotations == null)
770     {
771       annotations = new AnnotationPanel(av);
772     }
773
774     return annotations.adjustPanelHeight();
775   }
776
777   /**
778    * Draws the visible region of the alignment on the graphics context. If there
779    * are hidden column markers in the visible region, then each sub-region
780    * between the markers is drawn separately, followed by the hidden column
781    * marker.
782    * 
783    * @param g1
784    *          the graphics context, positioned at the first residue to be drawn
785    * @param startRes
786    *          offset of the first column to draw (0..)
787    * @param endRes
788    *          offset of the last column to draw (0..)
789    * @param startSeq
790    *          offset of the first sequence to draw (0..)
791    * @param endSeq
792    *          offset of the last sequence to draw (0..)
793    * @param yOffset
794    *          vertical offset at which to draw (for wrapped alignments)
795    */
796   public void drawPanel(Graphics g1, final int startRes, final int endRes,
797           final int startSeq, final int endSeq, final int yOffset)
798   {
799     updateViewport();
800     if (!av.hasHiddenColumns())
801     {
802       draw(g1, startRes, endRes, startSeq, endSeq, yOffset);
803     }
804     else
805     {
806       int screenY = 0;
807       final int screenYMax = endRes - startRes;
808       int blockStart = startRes;
809       int blockEnd = endRes;
810
811       for (int[] region : av.getAlignment().getHiddenColumns()
812               .getHiddenColumnsCopy())
813       {
814         int hideStart = region[0];
815         int hideEnd = region[1];
816
817         if (hideStart <= blockStart)
818         {
819           blockStart += (hideEnd - hideStart) + 1;
820           continue;
821         }
822
823         /*
824          * draw up to just before the next hidden region, or the end of
825          * the visible region, whichever comes first
826          */
827         blockEnd = Math.min(hideStart - 1, blockStart + screenYMax
828                 - screenY);
829
830         g1.translate(screenY * charWidth, 0);
831
832         draw(g1, blockStart, blockEnd, startSeq, endSeq, yOffset);
833
834         /*
835          * draw the downline of the hidden column marker (ScalePanel draws the
836          * triangle on top) if we reached it
837          */
838         if (av.getShowHiddenMarkers() && blockEnd == hideStart - 1)
839         {
840           g1.setColor(Color.blue);
841
842           g1.drawLine((blockEnd - blockStart + 1) * charWidth - 1,
843                   0 + yOffset, (blockEnd - blockStart + 1) * charWidth - 1,
844                   (endSeq - startSeq + 1) * charHeight + yOffset);
845         }
846
847         g1.translate(-screenY * charWidth, 0);
848         screenY += blockEnd - blockStart + 1;
849         blockStart = hideEnd + 1;
850
851         if (screenY > screenYMax)
852         {
853           // already rendered last block
854           return;
855         }
856       }
857
858       if (screenY <= screenYMax)
859       {
860         // remaining visible region to render
861         blockEnd = blockStart + screenYMax - screenY;
862         g1.translate(screenY * charWidth, 0);
863         draw(g1, blockStart, blockEnd, startSeq, endSeq, yOffset);
864
865         g1.translate(-screenY * charWidth, 0);
866       }
867     }
868
869   }
870
871   /**
872    * Draws a region of the visible alignment
873    * 
874    * @param g1
875    * @param startRes
876    *          offset of the first column in the visible region (0..)
877    * @param endRes
878    *          offset of the last column in the visible region (0..)
879    * @param startSeq
880    *          offset of the first sequence in the visible region (0..)
881    * @param endSeq
882    *          offset of the last sequence in the visible region (0..)
883    * @param yOffset
884    *          vertical offset at which to draw (for wrapped alignments)
885    */
886   private void draw(Graphics g, int startRes, int endRes, int startSeq,
887           int endSeq, int offset)
888   {
889     g.setFont(av.getFont());
890     sr.prepare(g, av.isRenderGaps());
891
892     SequenceI nextSeq;
893
894     // / First draw the sequences
895     // ///////////////////////////
896     for (int i = startSeq; i <= endSeq; i++)
897     {
898       nextSeq = av.getAlignment().getSequenceAt(i);
899       if (nextSeq == null)
900       {
901         // occasionally, a race condition occurs such that the alignment row is
902         // empty
903         continue;
904       }
905       sr.drawSequence(nextSeq, av.getAlignment().findAllGroups(nextSeq),
906               startRes, endRes, offset + ((i - startSeq) * charHeight));
907
908       if (av.isShowSequenceFeatures())
909       {
910         fr.drawSequence(g, nextSeq, startRes, endRes, offset
911                 + ((i - startSeq) * charHeight), false);
912       }
913
914       /*
915        * highlight search Results once sequence has been drawn
916        */
917       if (av.hasSearchResults())
918       {
919         SearchResultsI searchResults = av.getSearchResults();
920         int[] visibleResults = searchResults.getResults(nextSeq,
921                 startRes, endRes);
922         if (visibleResults != null)
923         {
924           for (int r = 0; r < visibleResults.length; r += 2)
925           {
926             sr.drawHighlightedText(nextSeq, visibleResults[r],
927                     visibleResults[r + 1], (visibleResults[r] - startRes)
928                             * charWidth, offset
929                             + ((i - startSeq) * charHeight));
930           }
931         }
932       }
933
934       if (av.cursorMode && cursorY == i && cursorX >= startRes
935               && cursorX <= endRes)
936       {
937         sr.drawCursor(nextSeq, cursorX, (cursorX - startRes) * charWidth,
938                 offset + ((i - startSeq) * charHeight));
939       }
940     }
941
942     if (av.getSelectionGroup() != null
943             || av.getAlignment().getGroups().size() > 0)
944     {
945       drawGroupsBoundaries(g, startRes, endRes, startSeq, endSeq, offset);
946     }
947
948   }
949
950   void drawGroupsBoundaries(Graphics g1, int startRes, int endRes,
951           int startSeq, int endSeq, int offset)
952   {
953     Graphics2D g = (Graphics2D) g1;
954     //
955     // ///////////////////////////////////
956     // Now outline any areas if necessary
957     // ///////////////////////////////////
958     SequenceGroup group = av.getSelectionGroup();
959
960     int sx = -1;
961     int sy = -1;
962     int ex = -1;
963     int groupIndex = -1;
964     int visWidth = (endRes - startRes + 1) * charWidth;
965
966     if ((group == null) && (av.getAlignment().getGroups().size() > 0))
967     {
968       group = av.getAlignment().getGroups().get(0);
969       groupIndex = 0;
970     }
971
972     if (group != null)
973     {
974       do
975       {
976         int oldY = -1;
977         int i = 0;
978         boolean inGroup = false;
979         int top = -1;
980         int bottom = -1;
981
982         for (i = startSeq; i <= endSeq; i++)
983         {
984           sx = (group.getStartRes() - startRes) * charWidth;
985           sy = offset + ((i - startSeq) * charHeight);
986           ex = (((group.getEndRes() + 1) - group.getStartRes()) * charWidth) - 1;
987
988           if (sx + ex < 0 || sx > visWidth)
989           {
990             continue;
991           }
992
993           if ((sx <= (endRes - startRes) * charWidth)
994                   && group.getSequences(null).contains(
995                           av.getAlignment().getSequenceAt(i)))
996           {
997             if ((bottom == -1)
998                     && !group.getSequences(null).contains(
999                             av.getAlignment().getSequenceAt(i + 1)))
1000             {
1001               bottom = sy + charHeight;
1002             }
1003
1004             if (!inGroup)
1005             {
1006               if (((top == -1) && (i == 0))
1007                       || !group.getSequences(null).contains(
1008                               av.getAlignment().getSequenceAt(i - 1)))
1009               {
1010                 top = sy;
1011               }
1012
1013               oldY = sy;
1014               inGroup = true;
1015
1016               if (group == av.getSelectionGroup())
1017               {
1018                 g.setStroke(new BasicStroke(1, BasicStroke.CAP_BUTT,
1019                         BasicStroke.JOIN_ROUND, 3f, new float[] { 5f, 3f },
1020                         0f));
1021                 g.setColor(Color.RED);
1022               }
1023               else
1024               {
1025                 g.setStroke(new BasicStroke());
1026                 g.setColor(group.getOutlineColour());
1027               }
1028             }
1029           }
1030           else
1031           {
1032             if (inGroup)
1033             {
1034               if (sx >= 0 && sx < visWidth)
1035               {
1036                 g.drawLine(sx, oldY, sx, sy);
1037               }
1038
1039               if (sx + ex < visWidth)
1040               {
1041                 g.drawLine(sx + ex, oldY, sx + ex, sy);
1042               }
1043
1044               if (sx < 0)
1045               {
1046                 ex += sx;
1047                 sx = 0;
1048               }
1049
1050               if (sx + ex > visWidth)
1051               {
1052                 ex = visWidth;
1053               }
1054
1055               else if (sx + ex >= (endRes - startRes + 1) * charWidth)
1056               {
1057                 ex = (endRes - startRes + 1) * charWidth;
1058               }
1059
1060               if (top != -1)
1061               {
1062                 g.drawLine(sx, top, sx + ex, top);
1063                 top = -1;
1064               }
1065
1066               if (bottom != -1)
1067               {
1068                 g.drawLine(sx, bottom, sx + ex, bottom);
1069                 bottom = -1;
1070               }
1071
1072               inGroup = false;
1073             }
1074           }
1075         }
1076
1077         if (inGroup)
1078         {
1079           sy = offset + ((i - startSeq) * charHeight);
1080           if (sx >= 0 && sx < visWidth)
1081           {
1082             g.drawLine(sx, oldY, sx, sy);
1083           }
1084
1085           if (sx + ex < visWidth)
1086           {
1087             g.drawLine(sx + ex, oldY, sx + ex, sy);
1088           }
1089
1090           if (sx < 0)
1091           {
1092             ex += sx;
1093             sx = 0;
1094           }
1095
1096           if (sx + ex > visWidth)
1097           {
1098             ex = visWidth;
1099           }
1100           else if (sx + ex >= (endRes - startRes + 1) * charWidth)
1101           {
1102             ex = (endRes - startRes + 1) * charWidth;
1103           }
1104
1105           if (top != -1)
1106           {
1107             g.drawLine(sx, top, sx + ex, top);
1108             top = -1;
1109           }
1110
1111           if (bottom != -1)
1112           {
1113             g.drawLine(sx, bottom - 1, sx + ex, bottom - 1);
1114             bottom = -1;
1115           }
1116
1117           inGroup = false;
1118         }
1119
1120         groupIndex++;
1121
1122         g.setStroke(new BasicStroke());
1123
1124         if (groupIndex >= av.getAlignment().getGroups().size())
1125         {
1126           break;
1127         }
1128
1129         group = av.getAlignment().getGroups().get(groupIndex);
1130
1131       } while (groupIndex < av.getAlignment().getGroups().size());
1132
1133     }
1134
1135   }
1136
1137   /**
1138    * Highlights search results in the visible region by rendering as white text
1139    * on a black background. Any previous highlighting is removed. Answers true
1140    * if any highlight was left on the visible alignment (so status bar should be
1141    * set to match), else false.
1142    * <p>
1143    * Currently fastPaint is not implemented for wrapped alignments. If a wrapped
1144    * alignment had to be scrolled to show the highlighted region, then it should
1145    * be fully redrawn, otherwise a fast paint can be performed. This argument
1146    * could be removed if fast paint of scrolled wrapped alignment is coded in
1147    * future (JAL-2609).
1148    * 
1149    * @param results
1150    * @param noFastPaint
1151    * @return
1152    */
1153   public boolean highlightSearchResults(SearchResultsI results,
1154           boolean noFastPaint)
1155   {
1156     if (fastpainting)
1157     {
1158       return false;
1159     }
1160     boolean wrapped = av.getWrapAlignment();
1161
1162     try
1163     {
1164       fastPaint = !noFastPaint;
1165       fastpainting = fastPaint;
1166
1167       updateViewport();
1168
1169       /*
1170        * to avoid redrawing the whole visible region, we instead
1171        * redraw just the minimal regions to remove previous highlights
1172        * and add new ones
1173        */
1174       SearchResultsI previous = av.getSearchResults();
1175       av.setSearchResults(results);
1176       boolean redrawn = false;
1177       boolean drawn = false;
1178       if (wrapped)
1179       {
1180         redrawn = drawMappedPositionsWrapped(previous);
1181         drawn = drawMappedPositionsWrapped(results);
1182         redrawn |= drawn;
1183       }
1184       else
1185       {
1186         redrawn = drawMappedPositions(previous);
1187         drawn = drawMappedPositions(results);
1188         redrawn |= drawn;
1189       }
1190
1191       /*
1192        * if highlights were either removed or added, repaint
1193        */
1194       if (redrawn)
1195       {
1196         repaint();
1197       }
1198
1199       /*
1200        * return true only if highlights were added
1201        */
1202       return drawn;
1203
1204     } finally
1205     {
1206       fastpainting = false;
1207     }
1208   }
1209
1210   /**
1211    * Redraws the minimal rectangle in the visible region (if any) that includes
1212    * mapped positions of the given search results. Whether or not positions are
1213    * highlighted depends on the SearchResults set on the Viewport. This allows
1214    * this method to be called to either clear or set highlighting. Answers true
1215    * if any positions were drawn (in which case a repaint is still required),
1216    * else false.
1217    * 
1218    * @param results
1219    * @return
1220    */
1221   protected boolean drawMappedPositions(SearchResultsI results)
1222   {
1223     if (results == null)
1224     {
1225       return false;
1226     }
1227
1228     /*
1229      * calculate the minimal rectangle to redraw that 
1230      * includes both new and existing search results
1231      */
1232     int firstSeq = Integer.MAX_VALUE;
1233     int lastSeq = -1;
1234     int firstCol = Integer.MAX_VALUE;
1235     int lastCol = -1;
1236     boolean matchFound = false;
1237
1238     ViewportRanges ranges = av.getRanges();
1239     int firstVisibleColumn = ranges.getStartRes();
1240     int lastVisibleColumn = ranges.getEndRes();
1241     AlignmentI alignment = av.getAlignment();
1242     if (av.hasHiddenColumns())
1243     {
1244       firstVisibleColumn = alignment.getHiddenColumns()
1245               .adjustForHiddenColumns(firstVisibleColumn);
1246       lastVisibleColumn = alignment.getHiddenColumns()
1247               .adjustForHiddenColumns(lastVisibleColumn);
1248     }
1249
1250     for (int seqNo = ranges.getStartSeq(); seqNo <= ranges
1251             .getEndSeq(); seqNo++)
1252     {
1253       SequenceI seq = alignment.getSequenceAt(seqNo);
1254
1255       int[] visibleResults = results.getResults(seq, firstVisibleColumn,
1256               lastVisibleColumn);
1257       if (visibleResults != null)
1258       {
1259         for (int i = 0; i < visibleResults.length - 1; i += 2)
1260         {
1261           int firstMatchedColumn = visibleResults[i];
1262           int lastMatchedColumn = visibleResults[i + 1];
1263           if (firstMatchedColumn <= lastVisibleColumn
1264                   && lastMatchedColumn >= firstVisibleColumn)
1265           {
1266             /*
1267              * found a search results match in the visible region - 
1268              * remember the first and last sequence matched, and the first
1269              * and last visible columns in the matched positions
1270              */
1271             matchFound = true;
1272             firstSeq = Math.min(firstSeq, seqNo);
1273             lastSeq = Math.max(lastSeq, seqNo);
1274             firstMatchedColumn = Math.max(firstMatchedColumn,
1275                     firstVisibleColumn);
1276             lastMatchedColumn = Math.min(lastMatchedColumn,
1277                     lastVisibleColumn);
1278             firstCol = Math.min(firstCol, firstMatchedColumn);
1279             lastCol = Math.max(lastCol, lastMatchedColumn);
1280           }
1281         }
1282       }
1283     }
1284
1285     if (matchFound)
1286     {
1287       if (av.hasHiddenColumns())
1288       {
1289         firstCol = alignment.getHiddenColumns()
1290                 .findColumnPosition(firstCol);
1291         lastCol = alignment.getHiddenColumns().findColumnPosition(lastCol);
1292       }
1293       int transX = (firstCol - ranges.getStartRes()) * av.getCharWidth();
1294       int transY = (firstSeq - ranges.getStartSeq()) * av.getCharHeight();
1295       gg.translate(transX, transY);
1296       drawPanel(gg, firstCol, lastCol, firstSeq, lastSeq, 0);
1297       gg.translate(-transX, -transY);
1298     }
1299
1300     return matchFound;
1301   }
1302
1303   @Override
1304   public void propertyChange(PropertyChangeEvent evt)
1305   {
1306     String eventName = evt.getPropertyName();
1307
1308     int scrollX = 0;
1309     if (eventName.equals(ViewportRanges.STARTRES))
1310     {
1311       // Make sure we're not trying to draw a panel
1312       // larger than the visible window
1313       ViewportRanges vpRanges = av.getRanges();
1314       scrollX = (int) evt.getNewValue() - (int) evt.getOldValue();
1315       int range = vpRanges.getEndRes() - vpRanges.getStartRes();
1316       if (scrollX > range)
1317       {
1318         scrollX = range;
1319       }
1320       else if (scrollX < -range)
1321       {
1322         scrollX = -range;
1323       }
1324     }
1325
1326     // Both scrolling and resizing change viewport ranges: scrolling changes
1327     // both start and end points, but resize only changes end values.
1328     // Here we only want to fastpaint on a scroll, with resize using a normal
1329     // paint, so scroll events are identified as changes to the horizontal or
1330     // vertical start value.
1331     if (eventName.equals(ViewportRanges.STARTRES))
1332     {
1333       // scroll - startres and endres both change
1334       if (av.getWrapAlignment())
1335       {
1336         fastPaintWrapped(scrollX);
1337       }
1338       else
1339       {
1340         fastPaint(scrollX, 0);
1341       }
1342     }
1343     else if (eventName.equals(ViewportRanges.STARTSEQ))
1344     {
1345       fastPaint(0, (int) evt.getNewValue() - (int) evt.getOldValue());
1346     }
1347   }
1348
1349   /**
1350    * Does a minimal update of the image for a scroll movement. This method
1351    * handles scroll movements of up to one width of the wrapped alignment (one
1352    * click in the vertical scrollbar). Larger movements (for example after a
1353    * scroll to highlight a mapped position) trigger a full redraw instead.
1354    * 
1355    * @param scrollX
1356    *          number of positions scrolled (right if positive, left if negative)
1357    */
1358   protected void fastPaintWrapped(int scrollX)
1359   {
1360     ViewportRanges ranges = av.getRanges();
1361
1362     if (Math.abs(scrollX) > ranges.getViewportWidth())
1363     {
1364       /*
1365        * shift of more than one view width is 
1366        * overcomplicated to handle in this method
1367        */
1368       fastPaint = false;
1369       repaint();
1370       return;
1371     }
1372
1373     if (fastpainting || gg == null)
1374     {
1375       return;
1376     }
1377
1378     fastPaint = true;
1379     fastpainting = true;
1380
1381     try
1382     {
1383       calculateWrappedGeometry(getWidth(), getHeight());
1384
1385       /*
1386        * relocate the regions of the alignment that are still visible
1387        */
1388       shiftWrappedAlignment(-scrollX);
1389
1390       /*
1391        * add new columns (sequence, annotation)
1392        * - at top left if scrollX < 0 
1393        * - at right of last two widths if scrollX > 0
1394        */
1395       if (scrollX < 0)
1396       {
1397         int startRes = ranges.getStartRes();
1398         drawWrappedWidth(gg, wrappedSpaceAboveAlignment, startRes, startRes
1399                 - scrollX - 1, getHeight());
1400       }
1401       else
1402       {
1403         fastPaintWrappedAddRight(scrollX);
1404       }
1405
1406       /*
1407        * draw all scales (if  shown) and hidden column markers
1408        */
1409       drawWrappedDecorators(gg, getHeight(), ranges.getStartRes());
1410
1411       repaint();
1412     } finally
1413     {
1414       fastpainting = false;
1415     }
1416   }
1417
1418   /**
1419    * Draws the specified number of columns at the 'end' (bottom right) of a
1420    * wrapped alignment view, including sequences and annotations if shown, but
1421    * not scales. Also draws the same number of columns at the right hand end of
1422    * the second last width shown, if the last width is not full height (so
1423    * cannot simply be copied from the graphics image).
1424    * 
1425    * @param columns
1426    */
1427   protected void fastPaintWrappedAddRight(int columns)
1428   {
1429     if (columns == 0)
1430     {
1431       return;
1432     }
1433
1434     ViewportRanges ranges = av.getRanges();
1435     int viewportWidth = ranges.getViewportWidth();
1436
1437     /**
1438      * draw full height alignment in the second last row, last columns, if the
1439      * last row was not full height
1440      */
1441     int visibleWidths = wrappedVisibleWidths;
1442     int canvasHeight = getHeight();
1443     boolean lastWidthPartHeight = (wrappedVisibleWidths * wrappedRepeatHeightPx) > canvasHeight;
1444
1445     if (lastWidthPartHeight)
1446     {
1447       int widthsAbove = visibleWidths - 2;
1448       int ypos = wrappedRepeatHeightPx * widthsAbove
1449               + wrappedSpaceAboveAlignment;
1450       int endRes = ranges.getEndRes();
1451       endRes += widthsAbove * viewportWidth;
1452       int startRes = endRes - columns;
1453       int xOffset = ((startRes - ranges.getStartRes()) % viewportWidth)
1454               * charWidth;
1455
1456       /*
1457        * white fill first to erase annotations
1458        */
1459       gg.translate(xOffset, 0);
1460       gg.setColor(Color.white);
1461       gg.fillRect(labelWidthWest, ypos,
1462               (endRes - startRes + 1) * charWidth, wrappedRepeatHeightPx);
1463       gg.translate(-xOffset, 0);
1464
1465       drawWrappedWidth(gg, ypos, startRes, endRes, canvasHeight);
1466     }
1467
1468     /*
1469      * y-offset for drawing last width is height of widths above,
1470      * plus one gap row
1471      */
1472     int widthsAbove = visibleWidths - 1;
1473     int ypos = wrappedRepeatHeightPx * widthsAbove
1474             + wrappedSpaceAboveAlignment;
1475     int endRes = ranges.getEndRes();
1476     endRes += widthsAbove * viewportWidth;
1477     endRes = Math.min(endRes, ranges.getVisibleAlignmentWidth());
1478     int startRes = endRes - columns + 1;
1479
1480     /*
1481      * white fill first to erase annotations
1482      */
1483     int xOffset = ((startRes - ranges.getStartRes()) % viewportWidth)
1484             * charWidth;
1485     gg.translate(xOffset, 0);
1486     gg.setColor(Color.white);
1487     int width = viewportWidth * charWidth - xOffset;
1488     gg.fillRect(labelWidthWest, ypos, width, wrappedRepeatHeightPx);
1489     gg.translate(-xOffset, 0);
1490
1491     gg.setFont(av.getFont());
1492     gg.setColor(Color.black);
1493
1494     drawWrappedWidth(gg, ypos, startRes, endRes, canvasHeight);
1495
1496     /*
1497      * and finally, white fill any space below the visible alignment
1498      */
1499     int heightBelow = canvasHeight - visibleWidths * wrappedRepeatHeightPx;
1500     if (heightBelow > 0)
1501     {
1502       gg.setColor(Color.white);
1503       gg.fillRect(0, canvasHeight - heightBelow, getWidth(), heightBelow);
1504     }
1505   }
1506
1507   /**
1508    * Shifts the visible alignment by the specified number of columns - left if
1509    * negative, right if positive. Copies and moves sequences and annotations (if
1510    * shown). Scales, hidden column markers and any newly visible columns must be
1511    * drawn separately.
1512    * 
1513    * @param positions
1514    */
1515   protected void shiftWrappedAlignment(int positions)
1516   {
1517     if (positions == 0)
1518     {
1519       return;
1520     }
1521
1522     int canvasHeight = getHeight();
1523     ViewportRanges ranges = av.getRanges();
1524     int viewportWidth = ranges.getViewportWidth();
1525     int widthToCopy = (ranges.getViewportWidth() - Math.abs(positions))
1526             * charWidth;
1527     int heightToCopy = wrappedRepeatHeightPx - wrappedSpaceAboveAlignment;
1528     int xMax = ranges.getVisibleAlignmentWidth();
1529
1530     if (positions > 0)
1531     {
1532       /*
1533        * shift right (after scroll left)
1534        * for each wrapped width (starting with the last), copy (width-positions) 
1535        * columns from the left margin to the right margin, and copy positions 
1536        * columns from the right margin of the row above (if any) to the 
1537        * left margin of the current row
1538        */
1539
1540       /*
1541        * get y-offset of last wrapped width, first row of sequences
1542        */
1543       int y = canvasHeight / wrappedRepeatHeightPx * wrappedRepeatHeightPx;
1544       y += wrappedSpaceAboveAlignment;
1545       int copyFromLeftStart = labelWidthWest;
1546       int copyFromRightStart = copyFromLeftStart + widthToCopy;
1547
1548       while (y >= 0)
1549       {
1550         gg.copyArea(copyFromLeftStart, y, widthToCopy, heightToCopy,
1551                 positions * charWidth, 0);
1552         if (y > 0)
1553         {
1554           gg.copyArea(copyFromRightStart, y - wrappedRepeatHeightPx,
1555                   positions * charWidth, heightToCopy, -widthToCopy,
1556                   wrappedRepeatHeightPx);
1557         }
1558
1559         y -= wrappedRepeatHeightPx;
1560       }
1561     }
1562     else
1563     {
1564       /*
1565        * shift left (after scroll right)
1566        * for each wrapped width (starting with the first), copy (width-positions) 
1567        * columns from the right margin to the left margin, and copy positions 
1568        * columns from the left margin of the row below (if any) to the 
1569        * right margin of the current row
1570        */
1571       int xpos = av.getRanges().getStartRes();
1572       int y = wrappedSpaceAboveAlignment;
1573       int copyFromRightStart = labelWidthWest - positions * charWidth;
1574
1575       while (y < canvasHeight)
1576       {
1577         gg.copyArea(copyFromRightStart, y, widthToCopy, heightToCopy,
1578                 positions * charWidth, 0);
1579         if (y + wrappedRepeatHeightPx < canvasHeight - wrappedRepeatHeightPx
1580                 && (xpos + viewportWidth <= xMax))
1581         {
1582           gg.copyArea(labelWidthWest, y + wrappedRepeatHeightPx, -positions
1583                   * charWidth, heightToCopy, widthToCopy,
1584                   -wrappedRepeatHeightPx);
1585         }
1586
1587         y += wrappedRepeatHeightPx;
1588         xpos += viewportWidth;
1589       }
1590     }
1591   }
1592
1593   /**
1594    * Redraws any positions in the search results in the visible region of a
1595    * wrapped alignment. Any highlights are drawn depending on the search results
1596    * set on the Viewport, not the <code>results</code> argument. This allows
1597    * this method to be called either to clear highlights (passing the previous
1598    * search results), or to draw new highlights.
1599    * 
1600    * @param results
1601    * @return
1602    */
1603   protected boolean drawMappedPositionsWrapped(SearchResultsI results)
1604   {
1605     if (results == null)
1606     {
1607       return false;
1608     }
1609   
1610     boolean matchFound = false;
1611
1612     int wrappedWidth = av.getWrappedWidth();
1613     int wrappedHeight = getRepeatHeightWrapped();
1614
1615     ViewportRanges ranges = av.getRanges();
1616     int canvasHeight = getHeight();
1617     int repeats = canvasHeight / wrappedHeight;
1618     if (canvasHeight / wrappedHeight > 0)
1619     {
1620       repeats++;
1621     }
1622
1623     int firstVisibleColumn = ranges.getStartRes();
1624     int lastVisibleColumn = ranges.getStartRes() + repeats
1625             * ranges.getViewportWidth() - 1;
1626
1627     AlignmentI alignment = av.getAlignment();
1628     if (av.hasHiddenColumns())
1629     {
1630       firstVisibleColumn = alignment.getHiddenColumns()
1631               .adjustForHiddenColumns(firstVisibleColumn);
1632       lastVisibleColumn = alignment.getHiddenColumns()
1633               .adjustForHiddenColumns(lastVisibleColumn);
1634     }
1635
1636     int gapHeight = charHeight * (av.getScaleAboveWrapped() ? 2 : 1);
1637
1638     for (int seqNo = ranges.getStartSeq(); seqNo <= ranges
1639             .getEndSeq(); seqNo++)
1640     {
1641       SequenceI seq = alignment.getSequenceAt(seqNo);
1642
1643       int[] visibleResults = results.getResults(seq, firstVisibleColumn,
1644               lastVisibleColumn);
1645       if (visibleResults != null)
1646       {
1647         for (int i = 0; i < visibleResults.length - 1; i += 2)
1648         {
1649           int firstMatchedColumn = visibleResults[i];
1650           int lastMatchedColumn = visibleResults[i + 1];
1651           if (firstMatchedColumn <= lastVisibleColumn
1652                   && lastMatchedColumn >= firstVisibleColumn)
1653           {
1654             /*
1655              * found a search results match in the visible region
1656              */
1657             firstMatchedColumn = Math.max(firstMatchedColumn,
1658                     firstVisibleColumn);
1659             lastMatchedColumn = Math.min(lastMatchedColumn,
1660                     lastVisibleColumn);
1661
1662             /*
1663              * draw each mapped position separately (as contiguous positions may
1664              * wrap across lines)
1665              */
1666             for (int mappedPos = firstMatchedColumn; mappedPos <= lastMatchedColumn; mappedPos++)
1667             {
1668               int displayColumn = mappedPos;
1669               if (av.hasHiddenColumns())
1670               {
1671                 displayColumn = alignment.getHiddenColumns()
1672                         .findColumnPosition(displayColumn);
1673               }
1674
1675               /*
1676                * transX: offset from left edge of canvas to residue position
1677                */
1678               int transX = labelWidthWest
1679                       + ((displayColumn - ranges.getStartRes()) % wrappedWidth)
1680                       * av.getCharWidth();
1681
1682               /*
1683                * transY: offset from top edge of canvas to residue position
1684                */
1685               int transY = gapHeight;
1686               transY += (displayColumn - ranges.getStartRes())
1687                       / wrappedWidth * wrappedHeight;
1688               transY += (seqNo - ranges.getStartSeq()) * av.getCharHeight();
1689
1690               /*
1691                * yOffset is from graphics origin to start of visible region
1692                */
1693               int yOffset = 0;// (displayColumn / wrappedWidth) * wrappedHeight;
1694               if (transY < getHeight())
1695               {
1696                 matchFound = true;
1697                 gg.translate(transX, transY);
1698                 drawPanel(gg, displayColumn, displayColumn, seqNo, seqNo,
1699                         yOffset);
1700                 gg.translate(-transX, -transY);
1701               }
1702             }
1703           }
1704         }
1705       }
1706     }
1707   
1708     return matchFound;
1709   }
1710
1711   /**
1712    * Answers the height in pixels of a repeating section of the wrapped
1713    * alignment, including space above, scale above if shown, sequences, and
1714    * annotation panel if shown
1715    * 
1716    * @return
1717    */
1718   protected int getRepeatHeightWrapped()
1719   {
1720     // gap (and maybe scale) above
1721     int repeatHeight = charHeight * (av.getScaleAboveWrapped() ? 2 : 1);
1722
1723     // add sequences
1724     repeatHeight += av.getRanges().getViewportHeight() * charHeight;
1725
1726     // add annotations panel height if shown
1727     repeatHeight += getAnnotationHeight();
1728
1729     return repeatHeight;
1730   }
1731 }