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