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