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