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