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