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