Merge branch 'bug/JAL-247pngShowHiddenSeqMarks' into trialMerge
[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 (excluding 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.getAlignment().getHeight()
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 g, 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     // mc 30/08/18 undone because gnu.jpdf.PDFGraphics doesn't handle
797     // get/setTransform
798
799     g.translate(xOffset, 0);
800
801     // When printing we have an extra clipped region,
802     // the Printable page which we need to account for here
803     Shape clip = g.getClip();
804     if (clip == null)
805     {
806       g.setClip(0, 0, viewportWidth * charWidth, canvasHeight);
807     }
808     else
809     {
810       g.setClip(0, (int) clip.getBounds().getY(),
811               viewportWidth * charWidth, (int) clip.getBounds().getHeight());
812     }
813
814
815     /*
816      * white fill the region to be drawn (so incremental fast paint doesn't
817      * scribble over an existing image)
818      */
819     g.setColor(Color.white);
820     g.fillRect(0, ypos, (endx - startColumn + 1) * charWidth,
821             wrappedRepeatHeightPx);
822
823     drawPanel(g, startColumn, endx, 0, av.getAlignment().getHeight() - 1,
824             ypos);
825
826     int cHeight = av.getAlignment().getHeight() * av.getCharHeight();
827
828     if (av.isShowAnnotation())
829     {
830       g.translate(0, cHeight + ypos + 3);
831       if (annotations == null)
832       {
833         annotations = new AnnotationPanel(av);
834       }
835
836       annotations.renderer.drawComponent(annotations, av, g, -1,
837               startColumn, endx + 1);
838       g.translate(0, -cHeight - ypos - 3);
839     }
840     // g.dispose();
841     g.translate(-xOffset, 0);
842 //    g.setClip(clip);
843   }
844
845   /**
846    * Draws scales left, right and above (if shown), and any hidden column
847    * markers, on all widths of the wrapped alignment
848    * 
849    * @param g
850    * @param startColumn
851    */
852   protected void drawWrappedDecorators(Graphics g, final int startColumn)
853   {
854     int charWidth = av.getCharWidth();
855
856     g.setFont(av.getFont());
857
858     g.setColor(Color.black);
859
860     int ypos = wrappedSpaceAboveAlignment;
861     ViewportRanges ranges = av.getRanges();
862     int viewportWidth = ranges.getViewportWidth();
863     int maxWidth = ranges.getVisibleAlignmentWidth();
864     int widthsDrawn = 0;
865     int startCol = startColumn;
866
867     while (widthsDrawn < wrappedVisibleWidths)
868     {
869       int endColumn = Math.min(maxWidth, startCol + viewportWidth - 1);
870
871       if (av.getScaleLeftWrapped())
872       {
873         drawVerticalScale(g, startCol, endColumn - 1, ypos, true);
874       }
875
876       if (av.getScaleRightWrapped())
877       {
878         int x = labelWidthWest + viewportWidth * charWidth;
879         
880         g.translate(x, 0);
881         drawVerticalScale(g, startCol, endColumn, ypos, false);
882         g.translate(-x, 0);
883       }
884
885       /*
886        * white fill region of scale above and hidden column markers
887        * (to support incremental fast paint of image)
888        */
889       g.translate(labelWidthWest, 0);
890       g.setColor(Color.white);
891       g.fillRect(0, ypos - wrappedSpaceAboveAlignment, viewportWidth
892               * charWidth + labelWidthWest, wrappedSpaceAboveAlignment);
893       g.setColor(Color.black);
894       g.translate(-labelWidthWest, 0);
895
896       g.translate(labelWidthWest, 0);
897
898       if (av.getScaleAboveWrapped())
899       {
900         drawNorthScale(g, startCol, endColumn, ypos);
901       }
902
903       if (av.hasHiddenColumns() && av.getShowHiddenMarkers())
904       {
905         drawHiddenColumnMarkers(g, ypos, startCol, endColumn);
906       }
907
908       g.translate(-labelWidthWest, 0);
909
910       ypos += wrappedRepeatHeightPx;
911       startCol += viewportWidth;
912       widthsDrawn++;
913     }
914   }
915
916   /**
917    * Draws markers (triangles) above hidden column positions between startColumn
918    * and endColumn.
919    * 
920    * @param g
921    * @param ypos
922    * @param startColumn
923    * @param endColumn
924    */
925   protected void drawHiddenColumnMarkers(Graphics g, int ypos,
926           int startColumn, int endColumn)
927   {
928     int charHeight = av.getCharHeight();
929     int charWidth = av.getCharWidth();
930
931     g.setColor(Color.blue);
932     int res;
933     HiddenColumns hidden = av.getAlignment().getHiddenColumns();
934
935     Iterator<Integer> it = hidden.getStartRegionIterator(startColumn,
936             endColumn);
937     while (it.hasNext())
938     {
939       res = it.next() - startColumn;
940
941       if (res < 0 || res > endColumn - startColumn + 1)
942       {
943         continue;
944       }
945
946       /*
947        * draw a downward-pointing triangle at the hidden columns location
948        * (before the following visible column)
949        */
950       int xMiddle = res * charWidth;
951       int[] xPoints = new int[] { xMiddle - charHeight / 4,
952           xMiddle + charHeight / 4, xMiddle };
953       int yTop = ypos - (charHeight / 2);
954       int[] yPoints = new int[] { yTop, yTop, yTop + 8 };
955       g.fillPolygon(xPoints, yPoints, 3);
956     }
957   }
958
959   /*
960    * Draw a selection group over a wrapped alignment
961    */
962   private void drawWrappedSelection(Graphics2D g, SequenceGroup group,
963           int canvasWidth,
964           int canvasHeight, int startRes)
965   {
966     int charHeight = av.getCharHeight();
967     int charWidth = av.getCharWidth();
968       
969     // height gap above each panel
970     int hgap = charHeight;
971     if (av.getScaleAboveWrapped())
972     {
973       hgap += charHeight;
974     }
975
976     int cWidth = (canvasWidth - labelWidthEast - labelWidthWest)
977             / charWidth;
978     int cHeight = av.getAlignment().getHeight() * charHeight;
979
980     int startx = startRes;
981     int endx;
982     int ypos = hgap; // vertical offset
983     int maxwidth = av.getAlignment().getWidth();
984
985     if (av.hasHiddenColumns())
986     {
987       maxwidth = av.getAlignment().getHiddenColumns()
988               .absoluteToVisibleColumn(maxwidth);
989     }
990
991     // chop the wrapped alignment extent up into panel-sized blocks and treat
992     // each block as if it were a block from an unwrapped alignment
993     while ((ypos <= canvasHeight) && (startx < maxwidth))
994     {
995       // set end value to be start + width, or maxwidth, whichever is smaller
996       endx = startx + cWidth - 1;
997
998       if (endx > maxwidth)
999       {
1000         endx = maxwidth;
1001       }
1002
1003       g.translate(labelWidthWest, 0);
1004
1005       drawUnwrappedSelection(g, group, startx, endx, 0,
1006               av.getAlignment().getHeight() - 1,
1007               ypos);
1008
1009       g.translate(-labelWidthWest, 0);
1010
1011       // update vertical offset
1012       ypos += cHeight + getAnnotationHeight() + hgap;
1013
1014       // update horizontal offset
1015       startx += cWidth;
1016     }
1017   }
1018
1019   int getAnnotationHeight()
1020   {
1021     if (!av.isShowAnnotation())
1022     {
1023       return 0;
1024     }
1025
1026     if (annotations == null)
1027     {
1028       annotations = new AnnotationPanel(av);
1029     }
1030
1031     return annotations.adjustPanelHeight();
1032   }
1033
1034   /**
1035    * Draws the visible region of the alignment on the graphics context. If there
1036    * are hidden column markers in the visible region, then each sub-region
1037    * between the markers is drawn separately, followed by the hidden column
1038    * marker.
1039    * 
1040    * @param g1
1041    *          the graphics context, positioned at the first residue to be drawn
1042    * @param startRes
1043    *          offset of the first column to draw (0..)
1044    * @param endRes
1045    *          offset of the last column to draw (0..)
1046    * @param startSeq
1047    *          offset of the first sequence to draw (0..)
1048    * @param endSeq
1049    *          offset of the last sequence to draw (0..)
1050    * @param yOffset
1051    *          vertical offset at which to draw (for wrapped alignments)
1052    */
1053   public void drawPanel(Graphics g1, final int startRes, final int endRes,
1054           final int startSeq, final int endSeq, final int yOffset)
1055   {
1056     int charHeight = av.getCharHeight();
1057     int charWidth = av.getCharWidth();
1058
1059     if (!av.hasHiddenColumns())
1060     {
1061       draw(g1, startRes, endRes, startSeq, endSeq, yOffset);
1062     }
1063     else
1064     {
1065       int screenY = 0;
1066       int blockStart;
1067       int blockEnd;
1068
1069       HiddenColumns hidden = av.getAlignment().getHiddenColumns();
1070       VisibleContigsIterator regions = hidden
1071               .getVisContigsIterator(startRes, endRes + 1, true);
1072
1073       while (regions.hasNext())
1074       {
1075         int[] region = regions.next();
1076         blockEnd = region[1];
1077         blockStart = region[0];
1078
1079         /*
1080          * draw up to just before the next hidden region, or the end of
1081          * the visible region, whichever comes first
1082          */
1083         g1.translate(screenY * charWidth, 0);
1084
1085         draw(g1, blockStart, blockEnd, startSeq, endSeq, yOffset);
1086
1087         /*
1088          * draw the downline of the hidden column marker (ScalePanel draws the
1089          * triangle on top) if we reached it
1090          */
1091         if (av.getShowHiddenMarkers()
1092                 && (regions.hasNext() || regions.endsAtHidden()))
1093         {
1094           g1.setColor(Color.blue);
1095
1096           g1.drawLine((blockEnd - blockStart + 1) * charWidth - 1,
1097                   0 + yOffset, (blockEnd - blockStart + 1) * charWidth - 1,
1098                   (endSeq - startSeq + 1) * charHeight + yOffset);
1099         }
1100
1101         g1.translate(-screenY * charWidth, 0);
1102         screenY += blockEnd - blockStart + 1;
1103       }
1104     }
1105
1106   }
1107
1108   /**
1109    * Draws a region of the visible alignment
1110    * 
1111    * @param g1
1112    * @param startRes
1113    *          offset of the first column in the visible region (0..)
1114    * @param endRes
1115    *          offset of the last column in the visible region (0..)
1116    * @param startSeq
1117    *          offset of the first sequence in the visible region (0..)
1118    * @param endSeq
1119    *          offset of the last sequence in the visible region (0..)
1120    * @param yOffset
1121    *          vertical offset at which to draw (for wrapped alignments)
1122    */
1123   private void draw(Graphics g, int startRes, int endRes, int startSeq,
1124           int endSeq, int offset)
1125   {
1126     int charHeight = av.getCharHeight();
1127     int charWidth = av.getCharWidth();
1128
1129     g.setFont(av.getFont());
1130     seqRdr.prepare(g, av.isRenderGaps());
1131
1132     SequenceI nextSeq;
1133
1134     // / First draw the sequences
1135     // ///////////////////////////
1136     for (int i = startSeq; i <= endSeq; i++)
1137     {
1138       nextSeq = av.getAlignment().getSequenceAt(i);
1139       if (nextSeq == null)
1140       {
1141         // occasionally, a race condition occurs such that the alignment row is
1142         // empty
1143         continue;
1144       }
1145       seqRdr.drawSequence(nextSeq, av.getAlignment().findAllGroups(nextSeq),
1146               startRes, endRes, offset + ((i - startSeq) * charHeight));
1147
1148       if (av.isShowSequenceFeatures())
1149       {
1150         fr.drawSequence(g, nextSeq, startRes, endRes,
1151                 offset + ((i - startSeq) * charHeight), false);
1152       }
1153
1154       /*
1155        * highlight search Results once sequence has been drawn
1156        */
1157       if (av.hasSearchResults())
1158       {
1159         SearchResultsI searchResults = av.getSearchResults();
1160         int[] visibleResults = searchResults.getResults(nextSeq, startRes,
1161                 endRes);
1162         if (visibleResults != null)
1163         {
1164           for (int r = 0; r < visibleResults.length; r += 2)
1165           {
1166             seqRdr.drawHighlightedText(nextSeq, visibleResults[r],
1167                     visibleResults[r + 1],
1168                     (visibleResults[r] - startRes) * charWidth,
1169                     offset + ((i - startSeq) * charHeight));
1170           }
1171         }
1172       }
1173     }
1174
1175     if (av.getSelectionGroup() != null
1176             || av.getAlignment().getGroups().size() > 0)
1177     {
1178       drawGroupsBoundaries(g, startRes, endRes, startSeq, endSeq, offset);
1179     }
1180
1181   }
1182
1183   void drawGroupsBoundaries(Graphics g1, int startRes, int endRes,
1184           int startSeq, int endSeq, int offset)
1185   {
1186     Graphics2D g = (Graphics2D) g1;
1187     //
1188     // ///////////////////////////////////
1189     // Now outline any areas if necessary
1190     // ///////////////////////////////////
1191
1192     SequenceGroup group = null;
1193     int groupIndex = -1;
1194
1195     if (av.getAlignment().getGroups().size() > 0)
1196     {
1197       group = av.getAlignment().getGroups().get(0);
1198       groupIndex = 0;
1199     }
1200
1201     if (group != null)
1202     {
1203       g.setStroke(new BasicStroke());
1204       
1205       do
1206       {
1207         g.setColor(group.getOutlineColour());
1208         drawPartialGroupOutline(g, group, startRes, endRes, startSeq,
1209                 endSeq, offset);
1210
1211         groupIndex++;
1212
1213         g.setStroke(new BasicStroke());
1214
1215         if (groupIndex >= av.getAlignment().getGroups().size())
1216         {
1217           break;
1218         }
1219
1220         group = av.getAlignment().getGroups().get(groupIndex);
1221
1222       } while (groupIndex < av.getAlignment().getGroups().size());
1223
1224     }
1225
1226   }
1227
1228
1229   /*
1230    * Draw the selection group as a separate image and overlay
1231    */
1232   private BufferedImage drawSelectionGroup(int startRes, int endRes,
1233           int startSeq, int endSeq)
1234   {
1235     // get a new image of the correct size
1236     BufferedImage selectionImage = setupImage();
1237
1238     if (selectionImage == null)
1239     {
1240       return null;
1241     }
1242
1243     SequenceGroup group = av.getSelectionGroup();
1244     if (group == null)
1245     {
1246       // nothing to draw
1247       return null;
1248     }
1249
1250     // set up drawing colour
1251     Graphics2D g = (Graphics2D) selectionImage.getGraphics();
1252
1253     setupSelectionGroup(g, selectionImage);
1254
1255     if (!av.getWrapAlignment())
1256     {
1257       drawUnwrappedSelection(g, group, startRes, endRes, startSeq, endSeq,
1258               0);
1259     }
1260     else
1261     {
1262       drawWrappedSelection(g, group, getWidth(), getHeight(),
1263               av.getRanges().getStartRes());
1264     }
1265
1266     g.dispose();
1267     return selectionImage;
1268   }
1269
1270   /**
1271    * Draw the cursor as a separate image and overlay
1272    * 
1273    * @param startRes
1274    *          start residue of area to draw cursor in
1275    * @param endRes
1276    *          end residue of area to draw cursor in
1277    * @param startSeq
1278    *          start sequence of area to draw cursor in
1279    * @param endSeq
1280    *          end sequence of are to draw cursor in
1281    * @return a transparent image of the same size as the sequence canvas, with
1282    *         the cursor drawn on it, if any
1283    */
1284   private void drawCursor(Graphics g, int startRes, int endRes,
1285           int startSeq,
1286           int endSeq)
1287   {
1288     // convert the cursorY into a position on the visible alignment
1289     int cursor_ypos = cursorY;
1290
1291     // don't do work unless we have to
1292     if (cursor_ypos >= startSeq && cursor_ypos <= endSeq)
1293     {
1294       int yoffset = 0;
1295       int xoffset = 0;
1296       int startx = startRes;
1297       int endx = endRes;
1298
1299       // convert the cursorX into a position on the visible alignment
1300       int cursor_xpos = av.getAlignment().getHiddenColumns()
1301               .absoluteToVisibleColumn(cursorX);
1302
1303       if (av.getAlignment().getHiddenColumns().isVisible(cursorX))
1304       {
1305
1306         if (av.getWrapAlignment())
1307         {
1308           // work out the correct offsets for the cursor
1309           int charHeight = av.getCharHeight();
1310           int charWidth = av.getCharWidth();
1311           int canvasWidth = getWidth();
1312           int canvasHeight = getHeight();
1313
1314           // height gap above each panel
1315           int hgap = charHeight;
1316           if (av.getScaleAboveWrapped())
1317           {
1318             hgap += charHeight;
1319           }
1320
1321           int cWidth = (canvasWidth - labelWidthEast - labelWidthWest)
1322                   / charWidth;
1323           int cHeight = av.getAlignment().getHeight() * charHeight;
1324
1325           endx = startx + cWidth - 1;
1326           int ypos = hgap; // vertical offset
1327
1328           // iterate down the wrapped panels
1329           while ((ypos <= canvasHeight) && (endx < cursor_xpos))
1330           {
1331             // update vertical offset
1332             ypos += cHeight + getAnnotationHeight() + hgap;
1333
1334             // update horizontal offset
1335             startx += cWidth;
1336             endx = startx + cWidth - 1;
1337           }
1338           yoffset = ypos;
1339           xoffset = labelWidthWest;
1340         }
1341
1342         // now check if cursor is within range for x values
1343         if (cursor_xpos >= startx && cursor_xpos <= endx)
1344         {
1345           // get the character the cursor is drawn at
1346           SequenceI seq = av.getAlignment().getSequenceAt(cursorY);
1347           char s = seq.getCharAt(cursorX);
1348
1349           seqRdr.drawCursor(g, s,
1350                   xoffset + (cursor_xpos - startx) * av.getCharWidth(),
1351                   yoffset + (cursor_ypos - startSeq) * av.getCharHeight());
1352         }
1353       }
1354     }
1355   }
1356
1357
1358   /*
1359    * Set up graphics for selection group
1360    */
1361   private void setupSelectionGroup(Graphics2D g,
1362           BufferedImage selectionImage)
1363   {
1364     // set background to transparent
1365     g.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f));
1366     g.fillRect(0, 0, selectionImage.getWidth(), selectionImage.getHeight());
1367
1368     // set up foreground to draw red dashed line
1369     g.setComposite(AlphaComposite.Src);
1370     g.setStroke(new BasicStroke(1, BasicStroke.CAP_BUTT,
1371             BasicStroke.JOIN_ROUND, 3f, new float[]
1372     { 5f, 3f }, 0f));
1373     g.setColor(Color.RED);
1374   }
1375
1376   /*
1377    * Draw a selection group over an unwrapped alignment
1378    * @param g graphics object to draw with
1379    * @param group selection group
1380    * @param startRes start residue of area to draw
1381    * @param endRes end residue of area to draw
1382    * @param startSeq start sequence of area to draw
1383    * @param endSeq end sequence of area to draw
1384    * @param offset vertical offset (used when called from wrapped alignment code)
1385    */
1386   private void drawUnwrappedSelection(Graphics2D g, SequenceGroup group,
1387           int startRes, int endRes, int startSeq, int endSeq, int offset)
1388   {
1389     int charWidth = av.getCharWidth();
1390           
1391     if (!av.hasHiddenColumns())
1392     {
1393       drawPartialGroupOutline(g, group, startRes, endRes, startSeq, endSeq,
1394               offset);
1395     }
1396     else
1397     {
1398       // package into blocks of visible columns
1399       int screenY = 0;
1400       int blockStart;
1401       int blockEnd;
1402
1403       HiddenColumns hidden = av.getAlignment().getHiddenColumns();
1404       VisibleContigsIterator regions = hidden
1405               .getVisContigsIterator(startRes, endRes + 1, true);
1406       while (regions.hasNext())
1407       {
1408         int[] region = regions.next();
1409         blockEnd = region[1];
1410         blockStart = region[0];
1411
1412         g.translate(screenY * charWidth, 0);
1413         drawPartialGroupOutline(g, group,
1414                 blockStart, blockEnd, startSeq, endSeq, offset);
1415
1416         g.translate(-screenY * charWidth, 0);
1417         screenY += blockEnd - blockStart + 1;
1418       }
1419     }
1420   }
1421
1422   /*
1423    * Draw the selection group as a separate image and overlay
1424    */
1425   private void drawPartialGroupOutline(Graphics2D g, SequenceGroup group,
1426           int startRes, int endRes, int startSeq, int endSeq,
1427           int verticalOffset)
1428   {
1429     int charHeight = av.getCharHeight();
1430     int charWidth = av.getCharWidth();
1431     int visWidth = (endRes - startRes + 1) * charWidth;
1432
1433     int oldY = -1;
1434     int i = 0;
1435     boolean inGroup = false;
1436     int top = -1;
1437     int bottom = -1;
1438     int sy = -1;
1439
1440     List<SequenceI> seqs = group.getSequences(null);
1441
1442     // position of start residue of group relative to startRes, in pixels
1443     int sx = (group.getStartRes() - startRes) * charWidth;
1444
1445     // width of group in pixels
1446     int xwidth = (((group.getEndRes() + 1) - group.getStartRes())
1447             * charWidth) - 1;
1448
1449     if (!(sx + xwidth < 0 || sx > visWidth))
1450     {
1451       for (i = startSeq; i <= endSeq; i++)
1452       {
1453         sy = verticalOffset + (i - startSeq) * charHeight;
1454
1455         if ((sx <= (endRes - startRes) * charWidth)
1456                 && seqs.contains(av.getAlignment().getSequenceAt(i)))
1457         {
1458           if ((bottom == -1)
1459                   && !seqs.contains(av.getAlignment().getSequenceAt(i + 1)))
1460           {
1461             bottom = sy + charHeight;
1462           }
1463
1464           if (!inGroup)
1465           {
1466             if (((top == -1) && (i == 0)) || !seqs
1467                     .contains(av.getAlignment().getSequenceAt(i - 1)))
1468             {
1469               top = sy;
1470             }
1471
1472             oldY = sy;
1473             inGroup = true;
1474           }
1475         }
1476         else if (inGroup)
1477         {
1478           drawVerticals(g, sx, xwidth, visWidth, oldY, sy);
1479           drawHorizontals(g, sx, xwidth, visWidth, top, bottom);
1480
1481           // reset top and bottom
1482           top = -1;
1483           bottom = -1;
1484           inGroup = false;
1485         }
1486       }
1487       if (inGroup)
1488       {
1489         sy = verticalOffset + ((i - startSeq) * charHeight);
1490         drawVerticals(g, sx, xwidth, visWidth, oldY, sy);
1491         drawHorizontals(g, sx, xwidth, visWidth, top, bottom);
1492       }
1493     }
1494   }
1495
1496   /**
1497    * Draw horizontal selection group boundaries at top and bottom positions
1498    * 
1499    * @param g
1500    *          graphics object to draw on
1501    * @param sx
1502    *          start x position
1503    * @param xwidth
1504    *          width of gap
1505    * @param visWidth
1506    *          visWidth maximum available width
1507    * @param top
1508    *          position to draw top of group at
1509    * @param bottom
1510    *          position to draw bottom of group at
1511    */
1512   private void drawHorizontals(Graphics2D g, int sx, int xwidth,
1513           int visWidth, int top, int bottom)
1514   {
1515     int width = xwidth;
1516     int startx = sx;
1517     if (startx < 0)
1518     {
1519       width += startx;
1520       startx = 0;
1521     }
1522
1523     // don't let width extend beyond current block, or group extent
1524     // fixes JAL-2672
1525     if (startx + width >= visWidth)
1526     {
1527       width = visWidth - startx;
1528     }
1529
1530     if (top != -1)
1531     {
1532       g.drawLine(startx, top, startx + width, top);
1533     }
1534
1535     if (bottom != -1)
1536     {
1537       g.drawLine(startx, bottom - 1, startx + width, bottom - 1);
1538     }
1539   }
1540
1541   /**
1542    * Draw vertical lines at sx and sx+xwidth providing they lie within
1543    * [0,visWidth)
1544    * 
1545    * @param g
1546    *          graphics object to draw on
1547    * @param sx
1548    *          start x position
1549    * @param xwidth
1550    *          width of gap
1551    * @param visWidth
1552    *          visWidth maximum available width
1553    * @param oldY
1554    *          top y value
1555    * @param sy
1556    *          bottom y value
1557    */
1558   private void drawVerticals(Graphics2D g, int sx, int xwidth, int visWidth,
1559           int oldY, int sy)
1560   {
1561     // if start position is visible, draw vertical line to left of
1562     // group
1563     if (sx >= 0 && sx < visWidth)
1564     {
1565       g.drawLine(sx, oldY, sx, sy);
1566     }
1567
1568     // if end position is visible, draw vertical line to right of
1569     // group
1570     if (sx + xwidth < visWidth)
1571     {
1572       g.drawLine(sx + xwidth, oldY, sx + xwidth, sy);
1573     }
1574   }
1575   
1576   /**
1577    * Highlights search results in the visible region by rendering as white text
1578    * on a black background. Any previous highlighting is removed. Answers true
1579    * if any highlight was left on the visible alignment (so status bar should be
1580    * set to match), else false. This method does _not_ set the 'fastPaint' flag,
1581    * so allows the next repaint to update the whole display.
1582    * 
1583    * @param results
1584    * @return
1585    */
1586   public boolean highlightSearchResults(SearchResultsI results)
1587   {
1588     return highlightSearchResults(results, false);
1589
1590   }
1591   
1592   /**
1593    * Highlights search results in the visible region by rendering as white text
1594    * on a black background. Any previous highlighting is removed. Answers true
1595    * if any highlight was left on the visible alignment (so status bar should be
1596    * set to match), else false.
1597    * <p>
1598    * Optionally, set the 'fastPaint' flag for a faster redraw if only the
1599    * highlighted regions are modified. This speeds up highlighting across linked
1600    * alignments.
1601    * <p>
1602    * Currently fastPaint is not implemented for scrolled wrapped alignments. If
1603    * a wrapped alignment had to be scrolled to show the highlighted region, then
1604    * it should be fully redrawn, otherwise a fast paint can be performed. This
1605    * argument could be removed if fast paint of scrolled wrapped alignment is
1606    * coded in future (JAL-2609).
1607    * 
1608    * @param results
1609    * @param doFastPaint
1610    *          if true, sets a flag so the next repaint only redraws the modified
1611    *          image
1612    * @return
1613    */
1614   public boolean highlightSearchResults(SearchResultsI results,
1615           boolean doFastPaint)
1616   {
1617     if (fastpainting)
1618     {
1619       return false;
1620     }
1621     boolean wrapped = av.getWrapAlignment();
1622     try
1623     {
1624       fastPaint = doFastPaint;
1625       fastpainting = fastPaint;
1626
1627       /*
1628        * to avoid redrawing the whole visible region, we instead
1629        * redraw just the minimal regions to remove previous highlights
1630        * and add new ones
1631        */
1632       SearchResultsI previous = av.getSearchResults();
1633       av.setSearchResults(results);
1634       boolean redrawn = false;
1635       boolean drawn = false;
1636       if (wrapped)
1637       {
1638         redrawn = drawMappedPositionsWrapped(previous);
1639         drawn = drawMappedPositionsWrapped(results);
1640         redrawn |= drawn;
1641       }
1642       else
1643       {
1644         redrawn = drawMappedPositions(previous);
1645         drawn = drawMappedPositions(results);
1646         redrawn |= drawn;
1647       }
1648
1649       /*
1650        * if highlights were either removed or added, repaint
1651        */
1652       if (redrawn)
1653       {
1654         repaint();
1655       }
1656
1657       /*
1658        * return true only if highlights were added
1659        */
1660       return drawn;
1661
1662     } finally
1663     {
1664       fastpainting = false;
1665     }
1666   }
1667
1668   /**
1669    * Redraws the minimal rectangle in the visible region (if any) that includes
1670    * mapped positions of the given search results. Whether or not positions are
1671    * highlighted depends on the SearchResults set on the Viewport. This allows
1672    * this method to be called to either clear or set highlighting. Answers true
1673    * if any positions were drawn (in which case a repaint is still required),
1674    * else false.
1675    * 
1676    * @param results
1677    * @return
1678    */
1679   protected boolean drawMappedPositions(SearchResultsI results)
1680   {
1681     if ((results == null) || (img == null)) // JAL-2784 check gg is not null
1682     {
1683       return false;
1684     }
1685
1686     /*
1687      * calculate the minimal rectangle to redraw that 
1688      * includes both new and existing search results
1689      */
1690     int firstSeq = Integer.MAX_VALUE;
1691     int lastSeq = -1;
1692     int firstCol = Integer.MAX_VALUE;
1693     int lastCol = -1;
1694     boolean matchFound = false;
1695
1696     ViewportRanges ranges = av.getRanges();
1697     int firstVisibleColumn = ranges.getStartRes();
1698     int lastVisibleColumn = ranges.getEndRes();
1699     AlignmentI alignment = av.getAlignment();
1700     if (av.hasHiddenColumns())
1701     {
1702       firstVisibleColumn = alignment.getHiddenColumns()
1703               .visibleToAbsoluteColumn(firstVisibleColumn);
1704       lastVisibleColumn = alignment.getHiddenColumns()
1705               .visibleToAbsoluteColumn(lastVisibleColumn);
1706     }
1707
1708     for (int seqNo = ranges.getStartSeq(); seqNo <= ranges
1709             .getEndSeq(); seqNo++)
1710     {
1711       SequenceI seq = alignment.getSequenceAt(seqNo);
1712
1713       int[] visibleResults = results.getResults(seq, firstVisibleColumn,
1714               lastVisibleColumn);
1715       if (visibleResults != null)
1716       {
1717         for (int i = 0; i < visibleResults.length - 1; i += 2)
1718         {
1719           int firstMatchedColumn = visibleResults[i];
1720           int lastMatchedColumn = visibleResults[i + 1];
1721           if (firstMatchedColumn <= lastVisibleColumn
1722                   && lastMatchedColumn >= firstVisibleColumn)
1723           {
1724             /*
1725              * found a search results match in the visible region - 
1726              * remember the first and last sequence matched, and the first
1727              * and last visible columns in the matched positions
1728              */
1729             matchFound = true;
1730             firstSeq = Math.min(firstSeq, seqNo);
1731             lastSeq = Math.max(lastSeq, seqNo);
1732             firstMatchedColumn = Math.max(firstMatchedColumn,
1733                     firstVisibleColumn);
1734             lastMatchedColumn = Math.min(lastMatchedColumn,
1735                     lastVisibleColumn);
1736             firstCol = Math.min(firstCol, firstMatchedColumn);
1737             lastCol = Math.max(lastCol, lastMatchedColumn);
1738           }
1739         }
1740       }
1741     }
1742
1743     if (matchFound)
1744     {
1745       if (av.hasHiddenColumns())
1746       {
1747         firstCol = alignment.getHiddenColumns()
1748                 .absoluteToVisibleColumn(firstCol);
1749         lastCol = alignment.getHiddenColumns().absoluteToVisibleColumn(lastCol);
1750       }
1751       int transX = (firstCol - ranges.getStartRes()) * av.getCharWidth();
1752       int transY = (firstSeq - ranges.getStartSeq()) * av.getCharHeight();
1753       Graphics gg = img.getGraphics();
1754       gg.translate(transX, transY);
1755       drawPanel(gg, firstCol, lastCol, firstSeq, lastSeq, 0);
1756       gg.translate(-transX, -transY);
1757       gg.dispose();
1758     }
1759
1760     return matchFound;
1761   }
1762
1763   @Override
1764   public void propertyChange(PropertyChangeEvent evt)
1765   {
1766     String eventName = evt.getPropertyName();
1767
1768     if (eventName.equals(SequenceGroup.SEQ_GROUP_CHANGED))
1769     {
1770       fastPaint = true;
1771       repaint();
1772       return;
1773     }
1774     else if (eventName.equals(ViewportRanges.MOVE_VIEWPORT))
1775     {
1776       fastPaint = false;
1777       repaint();
1778       return;
1779     }
1780
1781     int scrollX = 0;
1782     if (eventName.equals(ViewportRanges.STARTRES)
1783             || eventName.equals(ViewportRanges.STARTRESANDSEQ))
1784     {
1785       // Make sure we're not trying to draw a panel
1786       // larger than the visible window
1787       if (eventName.equals(ViewportRanges.STARTRES))
1788       {
1789         scrollX = (int) evt.getNewValue() - (int) evt.getOldValue();
1790       }
1791       else
1792       {
1793         scrollX = ((int[]) evt.getNewValue())[0]
1794                 - ((int[]) evt.getOldValue())[0];
1795       }
1796       ViewportRanges vpRanges = av.getRanges();
1797
1798       int range = vpRanges.getEndRes() - vpRanges.getStartRes();
1799       if (scrollX > range)
1800       {
1801         scrollX = range;
1802       }
1803       else if (scrollX < -range)
1804       {
1805         scrollX = -range;
1806       }
1807     }
1808       // Both scrolling and resizing change viewport ranges: scrolling changes
1809       // both start and end points, but resize only changes end values.
1810       // Here we only want to fastpaint on a scroll, with resize using a normal
1811       // paint, so scroll events are identified as changes to the horizontal or
1812       // vertical start value.
1813       if (eventName.equals(ViewportRanges.STARTRES))
1814       {
1815           if (av.getWrapAlignment())
1816           {
1817             fastPaintWrapped(scrollX);
1818           }
1819           else
1820           {
1821             fastPaint(scrollX, 0);
1822           }
1823       }
1824       else if (eventName.equals(ViewportRanges.STARTSEQ))
1825       {
1826         // scroll
1827         fastPaint(0, (int) evt.getNewValue() - (int) evt.getOldValue());
1828       }
1829       else if (eventName.equals(ViewportRanges.STARTRESANDSEQ))
1830       {
1831         if (av.getWrapAlignment())
1832         {
1833           fastPaintWrapped(scrollX);
1834         }
1835         else
1836         {
1837           fastPaint(scrollX, 0);
1838         }
1839     }
1840     else if (eventName.equals(ViewportRanges.STARTSEQ))
1841     {
1842       // scroll
1843       fastPaint(0, (int) evt.getNewValue() - (int) evt.getOldValue());
1844     }
1845     else if (eventName.equals(ViewportRanges.STARTRESANDSEQ))
1846     {
1847       if (av.getWrapAlignment())
1848       {
1849         fastPaintWrapped(scrollX);
1850       }
1851     }
1852   }
1853
1854   /**
1855    * Does a minimal update of the image for a scroll movement. This method
1856    * handles scroll movements of up to one width of the wrapped alignment (one
1857    * click in the vertical scrollbar). Larger movements (for example after a
1858    * scroll to highlight a mapped position) trigger a full redraw instead.
1859    * 
1860    * @param scrollX
1861    *          number of positions scrolled (right if positive, left if negative)
1862    */
1863   protected void fastPaintWrapped(int scrollX)
1864   {
1865     ViewportRanges ranges = av.getRanges();
1866
1867     if (Math.abs(scrollX) > ranges.getViewportWidth())
1868     {
1869       /*
1870        * shift of more than one view width is 
1871        * overcomplicated to handle in this method
1872        */
1873       fastPaint = false;
1874       repaint();
1875       return;
1876     }
1877
1878     if (fastpainting || img == null)
1879     {
1880       return;
1881     }
1882
1883     fastPaint = true;
1884     fastpainting = true;
1885
1886     try
1887     {
1888       
1889       Graphics gg = img.getGraphics();
1890       
1891       calculateWrappedGeometry(getWidth(), getHeight());
1892
1893       /*
1894        * relocate the regions of the alignment that are still visible
1895        */
1896       shiftWrappedAlignment(-scrollX);
1897
1898       /*
1899        * add new columns (sequence, annotation)
1900        * - at top left if scrollX < 0 
1901        * - at right of last two widths if scrollX > 0
1902        */
1903       if (scrollX < 0)
1904       {
1905         int startRes = ranges.getStartRes();
1906         drawWrappedWidth(gg, wrappedSpaceAboveAlignment, startRes, startRes
1907                 - scrollX - 1, getHeight());
1908       }
1909       else
1910       {
1911         fastPaintWrappedAddRight(scrollX);
1912       }
1913
1914       /*
1915        * draw all scales (if  shown) and hidden column markers
1916        */
1917       drawWrappedDecorators(gg, ranges.getStartRes());
1918
1919       gg.dispose();
1920       
1921       repaint();
1922     } finally
1923     {
1924       fastpainting = false;
1925     }
1926   }
1927
1928   /**
1929    * Draws the specified number of columns at the 'end' (bottom right) of a
1930    * wrapped alignment view, including sequences and annotations if shown, but
1931    * not scales. Also draws the same number of columns at the right hand end of
1932    * the second last width shown, if the last width is not full height (so
1933    * cannot simply be copied from the graphics image).
1934    * 
1935    * @param columns
1936    */
1937   protected void fastPaintWrappedAddRight(int columns)
1938   {
1939     if (columns == 0)
1940     {
1941       return;
1942     }
1943
1944     Graphics gg = img.getGraphics();
1945     
1946     ViewportRanges ranges = av.getRanges();
1947     int viewportWidth = ranges.getViewportWidth();
1948     int charWidth = av.getCharWidth();
1949
1950     /**
1951      * draw full height alignment in the second last row, last columns, if the
1952      * last row was not full height
1953      */
1954     int visibleWidths = wrappedVisibleWidths;
1955     int canvasHeight = getHeight();
1956     boolean lastWidthPartHeight = (wrappedVisibleWidths * wrappedRepeatHeightPx) > canvasHeight;
1957
1958     if (lastWidthPartHeight)
1959     {
1960       int widthsAbove = Math.max(0, visibleWidths - 2);
1961       int ypos = wrappedRepeatHeightPx * widthsAbove
1962               + wrappedSpaceAboveAlignment;
1963       int endRes = ranges.getEndRes();
1964       endRes += widthsAbove * viewportWidth;
1965       int startRes = endRes - columns;
1966       int xOffset = ((startRes - ranges.getStartRes()) % viewportWidth)
1967               * charWidth;
1968
1969       /*
1970        * white fill first to erase annotations
1971        */
1972       
1973       
1974       gg.translate(xOffset, 0);
1975       gg.setColor(Color.white);
1976       gg.fillRect(labelWidthWest, ypos,
1977               (endRes - startRes + 1) * charWidth, wrappedRepeatHeightPx);
1978       gg.translate(-xOffset, 0);
1979
1980       drawWrappedWidth(gg, ypos, startRes, endRes, canvasHeight);
1981       
1982     }
1983
1984     /*
1985      * draw newly visible columns in last wrapped width (none if we
1986      * have reached the end of the alignment)
1987      * y-offset for drawing last width is height of widths above,
1988      * plus one gap row
1989      */
1990     int widthsAbove = visibleWidths - 1;
1991     int ypos = wrappedRepeatHeightPx * widthsAbove
1992             + wrappedSpaceAboveAlignment;
1993     int endRes = ranges.getEndRes();
1994     endRes += widthsAbove * viewportWidth;
1995     int startRes = endRes - columns + 1;
1996
1997     /*
1998      * white fill first to erase annotations
1999      */
2000     int xOffset = ((startRes - ranges.getStartRes()) % viewportWidth)
2001             * charWidth;
2002     gg.translate(xOffset, 0);
2003     gg.setColor(Color.white);
2004     int width = viewportWidth * charWidth - xOffset;
2005     gg.fillRect(labelWidthWest, ypos, width, wrappedRepeatHeightPx);
2006     gg.translate(-xOffset, 0);
2007
2008     gg.setFont(av.getFont());
2009     gg.setColor(Color.black);
2010
2011     if (startRes < ranges.getVisibleAlignmentWidth())
2012     {
2013       drawWrappedWidth(gg, ypos, startRes, endRes, canvasHeight);
2014     }
2015
2016     /*
2017      * and finally, white fill any space below the visible alignment
2018      */
2019     int heightBelow = canvasHeight - visibleWidths * wrappedRepeatHeightPx;
2020     if (heightBelow > 0)
2021     {
2022       gg.setColor(Color.white);
2023       gg.fillRect(0, canvasHeight - heightBelow, getWidth(), heightBelow);
2024     }
2025     gg.dispose();
2026  }
2027
2028   /**
2029    * Shifts the visible alignment by the specified number of columns - left if
2030    * negative, right if positive. Copies and moves sequences and annotations (if
2031    * shown). Scales, hidden column markers and any newly visible columns must be
2032    * drawn separately.
2033    * 
2034    * @param positions
2035    */
2036   protected void shiftWrappedAlignment(int positions)
2037   {
2038     if (positions == 0)
2039     {
2040       return;
2041     }
2042
2043     Graphics gg = img.getGraphics();
2044
2045     int charWidth = av.getCharWidth();
2046
2047     int canvasHeight = getHeight();
2048     ViewportRanges ranges = av.getRanges();
2049     int viewportWidth = ranges.getViewportWidth();
2050     int widthToCopy = (ranges.getViewportWidth() - Math.abs(positions))
2051             * charWidth;
2052     int heightToCopy = wrappedRepeatHeightPx - wrappedSpaceAboveAlignment;
2053     int xMax = ranges.getVisibleAlignmentWidth();
2054
2055     if (positions > 0)
2056     {
2057       /*
2058        * shift right (after scroll left)
2059        * for each wrapped width (starting with the last), copy (width-positions) 
2060        * columns from the left margin to the right margin, and copy positions 
2061        * columns from the right margin of the row above (if any) to the 
2062        * left margin of the current row
2063        */
2064
2065       /*
2066        * get y-offset of last wrapped width, first row of sequences
2067        */
2068       int y = canvasHeight / wrappedRepeatHeightPx * wrappedRepeatHeightPx;
2069       y += wrappedSpaceAboveAlignment;
2070       int copyFromLeftStart = labelWidthWest;
2071       int copyFromRightStart = copyFromLeftStart + widthToCopy;
2072
2073       while (y >= 0)
2074       {
2075         gg.copyArea(copyFromLeftStart, y, widthToCopy, heightToCopy,
2076                 positions * charWidth, 0);
2077         if (y > 0)
2078         {
2079           gg.copyArea(copyFromRightStart, y - wrappedRepeatHeightPx,
2080                   positions * charWidth, heightToCopy, -widthToCopy,
2081                   wrappedRepeatHeightPx);
2082         }
2083
2084         y -= wrappedRepeatHeightPx;
2085       }
2086     }
2087     else
2088     {
2089       /*
2090        * shift left (after scroll right)
2091        * for each wrapped width (starting with the first), copy (width-positions) 
2092        * columns from the right margin to the left margin, and copy positions 
2093        * columns from the left margin of the row below (if any) to the 
2094        * right margin of the current row
2095        */
2096       int xpos = av.getRanges().getStartRes();
2097       int y = wrappedSpaceAboveAlignment;
2098       int copyFromRightStart = labelWidthWest - positions * charWidth;
2099
2100       while (y < canvasHeight)
2101       {
2102         gg.copyArea(copyFromRightStart, y, widthToCopy, heightToCopy,
2103                 positions * charWidth, 0);
2104         if (y + wrappedRepeatHeightPx < canvasHeight - wrappedRepeatHeightPx
2105                 && (xpos + viewportWidth <= xMax))
2106         {
2107           gg.copyArea(labelWidthWest, y + wrappedRepeatHeightPx, -positions
2108                   * charWidth, heightToCopy, widthToCopy,
2109                   -wrappedRepeatHeightPx);
2110         }
2111         y += wrappedRepeatHeightPx;
2112         xpos += viewportWidth;
2113       }
2114     }
2115     gg.dispose();
2116   }
2117
2118   
2119   /**
2120    * Redraws any positions in the search results in the visible region of a
2121    * wrapped alignment. Any highlights are drawn depending on the search results
2122    * set on the Viewport, not the <code>results</code> argument. This allows
2123    * this method to be called either to clear highlights (passing the previous
2124    * search results), or to draw new highlights.
2125    * 
2126    * @param results
2127    * @return
2128    */
2129   protected boolean drawMappedPositionsWrapped(SearchResultsI results)
2130   {
2131     if ((results == null) || (img == null)) // JAL-2784 check gg is not null
2132     {
2133       return false;
2134     }
2135     int charHeight = av.getCharHeight();
2136
2137     boolean matchFound = false;
2138
2139     calculateWrappedGeometry(getWidth(), getHeight());
2140     int wrappedWidth = av.getWrappedWidth();
2141     int wrappedHeight = wrappedRepeatHeightPx;
2142
2143     ViewportRanges ranges = av.getRanges();
2144     int canvasHeight = getHeight();
2145     int repeats = canvasHeight / wrappedHeight;
2146     if (canvasHeight / wrappedHeight > 0)
2147     {
2148       repeats++;
2149     }
2150
2151     int firstVisibleColumn = ranges.getStartRes();
2152     int lastVisibleColumn = ranges.getStartRes() + repeats
2153             * ranges.getViewportWidth() - 1;
2154
2155     AlignmentI alignment = av.getAlignment();
2156     if (av.hasHiddenColumns())
2157     {
2158       firstVisibleColumn = alignment.getHiddenColumns()
2159               .visibleToAbsoluteColumn(firstVisibleColumn);
2160       lastVisibleColumn = alignment.getHiddenColumns()
2161               .visibleToAbsoluteColumn(lastVisibleColumn);
2162     }
2163
2164     int gapHeight = charHeight * (av.getScaleAboveWrapped() ? 2 : 1);
2165
2166     
2167     Graphics gg = img.getGraphics();
2168
2169     for (int seqNo = ranges.getStartSeq(); seqNo <= ranges
2170             .getEndSeq(); seqNo++)
2171     {
2172       SequenceI seq = alignment.getSequenceAt(seqNo);
2173
2174       int[] visibleResults = results.getResults(seq, firstVisibleColumn,
2175               lastVisibleColumn);
2176       if (visibleResults != null)
2177       {
2178         for (int i = 0; i < visibleResults.length - 1; i += 2)
2179         {
2180           int firstMatchedColumn = visibleResults[i];
2181           int lastMatchedColumn = visibleResults[i + 1];
2182           if (firstMatchedColumn <= lastVisibleColumn
2183                   && lastMatchedColumn >= firstVisibleColumn)
2184           {
2185             /*
2186              * found a search results match in the visible region
2187              */
2188             firstMatchedColumn = Math.max(firstMatchedColumn,
2189                     firstVisibleColumn);
2190             lastMatchedColumn = Math.min(lastMatchedColumn,
2191                     lastVisibleColumn);
2192
2193             /*
2194              * draw each mapped position separately (as contiguous positions may
2195              * wrap across lines)
2196              */
2197             for (int mappedPos = firstMatchedColumn; mappedPos <= lastMatchedColumn; mappedPos++)
2198             {
2199               int displayColumn = mappedPos;
2200               if (av.hasHiddenColumns())
2201               {
2202                 displayColumn = alignment.getHiddenColumns()
2203                         .absoluteToVisibleColumn(displayColumn);
2204               }
2205
2206               /*
2207                * transX: offset from left edge of canvas to residue position
2208                */
2209               int transX = labelWidthWest
2210                       + ((displayColumn - ranges.getStartRes()) % wrappedWidth)
2211                       * av.getCharWidth();
2212
2213               /*
2214                * transY: offset from top edge of canvas to residue position
2215                */
2216               int transY = gapHeight;
2217               transY += (displayColumn - ranges.getStartRes())
2218                       / wrappedWidth * wrappedHeight;
2219               transY += (seqNo - ranges.getStartSeq()) * av.getCharHeight();
2220
2221               /*
2222                * yOffset is from graphics origin to start of visible region
2223                */
2224               int yOffset = 0;// (displayColumn / wrappedWidth) * wrappedHeight;
2225               if (transY < getHeight())
2226               {
2227                 matchFound = true;
2228                 gg.translate(transX, transY);
2229                 drawPanel(gg, displayColumn, displayColumn, seqNo, seqNo,
2230                         yOffset);
2231                 gg.translate(-transX, -transY);
2232               }
2233             }
2234           }
2235         }
2236       }
2237     }
2238   
2239     gg.dispose();
2240
2241     return matchFound;
2242   }
2243
2244   /**
2245    * Answers the width in pixels of the left scale labels (0 if not shown)
2246    * 
2247    * @return
2248    */
2249   int getLabelWidthWest()
2250   {
2251     return labelWidthWest;
2252   }
2253 }