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