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