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