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