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