Merge remote-tracking branch 'origin/releases/Release_2_10_2b1_Branch'
[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.viewmodel.ViewportListenerI;
31 import jalview.viewmodel.ViewportRanges;
32
33 import java.awt.AlphaComposite;
34 import java.awt.BasicStroke;
35 import java.awt.BorderLayout;
36 import java.awt.Color;
37 import java.awt.FontMetrics;
38 import java.awt.Graphics;
39 import java.awt.Graphics2D;
40 import java.awt.RenderingHints;
41 import java.awt.Shape;
42 import java.awt.image.BufferedImage;
43 import java.beans.PropertyChangeEvent;
44 import java.util.List;
45
46 import javax.swing.JComponent;
47
48 /**
49  * DOCUMENT ME!
50  * 
51  * @author $author$
52  * @version $Revision$
53  */
54 public class SeqCanvas extends JComponent implements ViewportListenerI
55 {
56   final FeatureRenderer fr;
57
58   final SequenceRenderer seqRdr;
59
60   BufferedImage img;
61
62   Graphics2D gg;
63
64   AlignViewport av;
65
66   boolean fastPaint = false;
67
68   int LABEL_WEST;
69
70   int LABEL_EAST;
71
72   int cursorX = 0;
73
74   int cursorY = 0;
75
76   int charHeight = 0;
77
78   int charWidth = 0;
79
80   boolean fastpainting = false;
81
82   AnnotationPanel annotations;
83
84   /**
85    * Creates a new SeqCanvas object.
86    * 
87    * @param av
88    *          DOCUMENT ME!
89    */
90   public SeqCanvas(AlignmentPanel ap)
91   {
92     this.av = ap.av;
93     updateViewport();
94     fr = new FeatureRenderer(ap);
95     seqRdr = new SequenceRenderer(av);
96     setLayout(new BorderLayout());
97     PaintRefresher.Register(this, av.getSequenceSetId());
98     setBackground(Color.white);
99
100     av.getRanges().addPropertyChangeListener(this);
101   }
102
103   public SequenceRenderer getSequenceRenderer()
104   {
105     return seqRdr;
106   }
107
108   public FeatureRenderer getFeatureRenderer()
109   {
110     return fr;
111   }
112
113   private void updateViewport()
114   {
115     charHeight = av.getCharHeight();
116     charWidth = av.getCharWidth();
117   }
118
119   /**
120    * DOCUMENT ME!
121    * 
122    * @param g
123    *          DOCUMENT ME!
124    * @param startx
125    *          DOCUMENT ME!
126    * @param endx
127    *          DOCUMENT ME!
128    * @param ypos
129    *          DOCUMENT ME!
130    */
131   private void drawNorthScale(Graphics g, int startx, int endx, int ypos)
132   {
133     updateViewport();
134     for (ScaleMark mark : new ScaleRenderer().calculateMarks(av, startx,
135             endx))
136     {
137       int mpos = mark.column; // (i - startx - 1)
138       if (mpos < 0)
139       {
140         continue;
141       }
142       String mstring = mark.text;
143
144       if (mark.major)
145       {
146         if (mstring != null)
147         {
148           g.drawString(mstring, mpos * charWidth, ypos - (charHeight / 2));
149         }
150         g.drawLine((mpos * charWidth) + (charWidth / 2),
151                 (ypos + 2) - (charHeight / 2),
152                 (mpos * charWidth) + (charWidth / 2), ypos - 2);
153       }
154     }
155   }
156
157   /**
158    * DOCUMENT ME!
159    * 
160    * @param g
161    *          DOCUMENT ME!
162    * @param startx
163    *          DOCUMENT ME!
164    * @param endx
165    *          DOCUMENT ME!
166    * @param ypos
167    *          DOCUMENT ME!
168    */
169   void drawWestScale(Graphics g, int startx, int endx, int ypos)
170   {
171     FontMetrics fm = getFontMetrics(av.getFont());
172     ypos += charHeight;
173
174     if (av.hasHiddenColumns())
175     {
176       startx = av.getAlignment().getHiddenColumns()
177               .adjustForHiddenColumns(startx);
178       endx = av.getAlignment().getHiddenColumns()
179               .adjustForHiddenColumns(endx);
180     }
181
182     int maxwidth = av.getAlignment().getWidth();
183     if (av.hasHiddenColumns())
184     {
185       maxwidth = av.getAlignment().getHiddenColumns()
186               .findColumnPosition(maxwidth) - 1;
187     }
188
189     // WEST SCALE
190     for (int i = 0; i < av.getAlignment().getHeight(); i++)
191     {
192       SequenceI seq = av.getAlignment().getSequenceAt(i);
193       int index = startx;
194       int value = -1;
195
196       while (index < endx)
197       {
198         if (jalview.util.Comparison.isGap(seq.getCharAt(index)))
199         {
200           index++;
201
202           continue;
203         }
204
205         value = av.getAlignment().getSequenceAt(i).findPosition(index);
206
207         break;
208       }
209
210       if (value != -1)
211       {
212         int x = LABEL_WEST - fm.stringWidth(String.valueOf(value))
213                 - charWidth / 2;
214         g.drawString(value + "", x,
215                 (ypos + (i * charHeight)) - (charHeight / 5));
216       }
217     }
218   }
219
220   /**
221    * DOCUMENT ME!
222    * 
223    * @param g
224    *          DOCUMENT ME!
225    * @param startx
226    *          DOCUMENT ME!
227    * @param endx
228    *          DOCUMENT ME!
229    * @param ypos
230    *          DOCUMENT ME!
231    */
232   void drawEastScale(Graphics g, int startx, int endx, int ypos)
233   {
234     ypos += charHeight;
235
236     if (av.hasHiddenColumns())
237     {
238       endx = av.getAlignment().getHiddenColumns()
239               .adjustForHiddenColumns(endx);
240     }
241
242     SequenceI seq;
243     // EAST SCALE
244     for (int i = 0; i < av.getAlignment().getHeight(); i++)
245     {
246       seq = av.getAlignment().getSequenceAt(i);
247       int index = endx;
248       int value = -1;
249
250       while (index > startx)
251       {
252         if (jalview.util.Comparison.isGap(seq.getCharAt(index)))
253         {
254           index--;
255
256           continue;
257         }
258
259         value = seq.findPosition(index);
260
261         break;
262       }
263
264       if (value != -1)
265       {
266         g.drawString(String.valueOf(value), 0,
267                 (ypos + (i * charHeight)) - (charHeight / 5));
268       }
269     }
270   }
271
272
273   /**
274    * need to make this thread safe move alignment rendering in response to
275    * slider adjustment
276    * 
277    * @param horizontal
278    *          shift along
279    * @param vertical
280    *          shift up or down in repaint
281    */
282   public void fastPaint(int horizontal, int vertical)
283   {
284     if (fastpainting || gg == null)
285     {
286       return;
287     }
288     fastpainting = true;
289     fastPaint = true;
290     updateViewport();
291
292     ViewportRanges ranges = av.getRanges();
293     int sr = ranges.getStartRes();
294     int er = ranges.getEndRes();
295     int ss = ranges.getStartSeq();
296     int es = ranges.getEndSeq();
297     int transX = 0;
298     int transY = 0;
299
300     gg.copyArea(horizontal * charWidth, vertical * charHeight,
301             img.getWidth(), img.getHeight(), -horizontal * charWidth,
302             -vertical * charHeight);
303
304     if (horizontal > 0) // scrollbar pulled right, image to the left
305     {
306       transX = (er - sr - horizontal) * charWidth;
307       sr = er - horizontal;
308     }
309     else if (horizontal < 0)
310     {
311       er = sr - horizontal;
312     }
313     else if (vertical > 0) // scroll down
314     {
315       ss = es - vertical;
316
317       if (ss < ranges.getStartSeq())
318       { // ie scrolling too fast, more than a page at a time
319         ss = ranges.getStartSeq();
320       }
321       else
322       {
323         transY = img.getHeight() - ((vertical + 1) * charHeight);
324       }
325     }
326     else if (vertical < 0)
327     {
328       es = ss - vertical;
329
330       if (es > ranges.getEndSeq())
331       {
332         es = ranges.getEndSeq();
333       }
334     }
335
336     gg.translate(transX, transY);
337     drawPanel(gg, sr, er, ss, es, 0);
338     gg.translate(-transX, -transY);
339
340     repaint();
341     fastpainting = false;
342   }
343
344   /**
345    * Definitions of startx and endx (hopefully): SMJS This is what I'm working
346    * towards! startx is the first residue (starting at 0) to display. endx is
347    * the last residue to display (starting at 0). starty is the first sequence
348    * to display (starting at 0). endy is the last sequence to display (starting
349    * at 0). NOTE 1: The av limits are set in setFont in this class and in the
350    * adjustment listener in SeqPanel when the scrollbars move.
351    */
352
353   // Set this to false to force a full panel paint
354   @Override
355   public void paintComponent(Graphics g)
356   {
357     super.paintComponent(g);
358
359     updateViewport();
360
361     ViewportRanges ranges = av.getRanges();
362
363     int width = getWidth();
364     int height = getHeight();
365
366     width -= (width % charWidth);
367     height -= (height % charHeight);
368
369     // selectImage is the selection group outline image
370     BufferedImage selectImage = drawSelectionGroup(
371             ranges.getStartRes(), ranges.getEndRes(),
372             ranges.getStartSeq(), ranges.getEndSeq());
373
374     if ((img != null) && (fastPaint
375             || (getVisibleRect().width != g.getClipBounds().width)
376             || (getVisibleRect().height != g.getClipBounds().height)))
377     {
378       BufferedImage lcimg = buildLocalImage(selectImage);
379       g.drawImage(lcimg, 0, 0, this);
380       fastPaint = false;
381     }
382     else if ((width > 0) && (height > 0))
383     {
384       // img is a cached version of the last view we drew, if any
385       // if we have no img or the size has changed, make a new one
386       if (img == null || width != img.getWidth()
387               || height != img.getHeight())
388       {
389         img = setupImage();
390         if (img == null)
391         {
392           return;
393         }
394         gg = (Graphics2D) img.getGraphics();
395         gg.setFont(av.getFont());
396       }
397
398       if (av.antiAlias)
399       {
400         gg.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
401                 RenderingHints.VALUE_ANTIALIAS_ON);
402       }
403
404       gg.setColor(Color.white);
405       gg.fillRect(0, 0, img.getWidth(), img.getHeight());
406
407       if (av.getWrapAlignment())
408       {
409         drawWrappedPanel(gg, getWidth(), getHeight(), ranges.getStartRes());
410       }
411       else
412       {
413         drawPanel(gg, ranges.getStartRes(), ranges.getEndRes(),
414                 ranges.getStartSeq(), ranges.getEndSeq(), 0);
415       }
416
417       // lcimg is a local *copy* of img which we'll draw selectImage on top of
418       BufferedImage lcimg = buildLocalImage(selectImage);
419       g.drawImage(lcimg, 0, 0, this);
420     }
421   }
422
423   /**
424    * Draw an alignment panel for printing
425    * 
426    * @param g1
427    *          Graphics object to draw with
428    * @param startRes
429    *          start residue of print area
430    * @param endRes
431    *          end residue of print area
432    * @param startSeq
433    *          start sequence of print area
434    * @param endSeq
435    *          end sequence of print area
436    */
437   public void drawPanelForPrint(Graphics g1, int startRes, int endRes,
438           int startSeq, int endSeq)
439   {
440     BufferedImage selectImage = drawSelectionGroup(startRes, endRes,
441             startSeq, endSeq);
442     drawPanel(g1, startRes, endRes, startSeq, endSeq, 0);
443     ((Graphics2D) g1).setComposite(
444             AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
445     g1.drawImage(selectImage, 0, 0, this);
446   }
447
448   /*
449    * Make a local image by combining the cached image img
450    * with any selection
451    */
452   private BufferedImage buildLocalImage(BufferedImage selectImage)
453   {
454     // clone the cached image
455     BufferedImage lcimg = new BufferedImage(img.getWidth(), img.getHeight(),
456             img.getType());
457     Graphics2D g2d = lcimg.createGraphics();
458     g2d.drawImage(img, 0, 0, null);
459
460     // overlay selection group on lcimg
461     if (selectImage != null)
462     {
463       g2d.setComposite(
464               AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
465       g2d.drawImage(selectImage, 0, 0, this);
466     }
467     g2d.dispose();
468
469     return lcimg;
470   }
471
472   /*
473    * Set up a buffered image of the correct height and size for the sequence canvas
474    */
475   private BufferedImage setupImage()
476   {
477     BufferedImage lcimg = null;
478
479     int width = getWidth();
480     int height = getHeight();
481
482     width -= (width % charWidth);
483     height -= (height % charHeight);
484
485     if ((width < 1) || (height < 1))
486     {
487       return null;
488     }
489
490     try
491     {
492       lcimg = new BufferedImage(width, height,
493               BufferedImage.TYPE_INT_ARGB); // ARGB so alpha compositing works
494     } catch (OutOfMemoryError er)
495     {
496       System.gc();
497       System.err.println(
498               "Group image OutOfMemory Redraw Error.\n" + er);
499       new OOMWarning("Creating alignment image for display", er);
500
501       return null;
502     }
503
504     return lcimg;
505   }
506
507   /**
508    * DOCUMENT ME!
509    * 
510    * @param cwidth
511    *          DOCUMENT ME!
512    * 
513    * @return DOCUMENT ME!
514    */
515   public int getWrappedCanvasWidth(int cwidth)
516   {
517     FontMetrics fm = getFontMetrics(av.getFont());
518
519     LABEL_EAST = 0;
520     LABEL_WEST = 0;
521
522     if (av.getScaleRightWrapped())
523     {
524       LABEL_EAST = fm.stringWidth(getMask());
525     }
526
527     if (av.getScaleLeftWrapped())
528     {
529       LABEL_WEST = fm.stringWidth(getMask());
530     }
531
532     return (cwidth - LABEL_EAST - LABEL_WEST) / charWidth;
533   }
534
535   /**
536    * Generates a string of zeroes.
537    * 
538    * @return String
539    */
540   String getMask()
541   {
542     String mask = "00";
543     int maxWidth = 0;
544     int tmp;
545     for (int i = 0; i < av.getAlignment().getHeight(); i++)
546     {
547       tmp = av.getAlignment().getSequenceAt(i).getEnd();
548       if (tmp > maxWidth)
549       {
550         maxWidth = tmp;
551       }
552     }
553
554     for (int i = maxWidth; i > 0; i /= 10)
555     {
556       mask += "0";
557     }
558     return mask;
559   }
560
561   /**
562    * DOCUMENT ME!
563    * 
564    * @param g
565    *          DOCUMENT ME!
566    * @param canvasWidth
567    *          DOCUMENT ME!
568    * @param canvasHeight
569    *          DOCUMENT ME!
570    * @param startRes
571    *          DOCUMENT ME!
572    */
573   public void drawWrappedPanel(Graphics g, int canvasWidth,
574           int canvasHeight, int startRes)
575   {
576     updateViewport();
577     AlignmentI al = av.getAlignment();
578
579     FontMetrics fm = getFontMetrics(av.getFont());
580
581     LABEL_EAST = 0;
582     LABEL_WEST = 0;
583
584     if (av.getScaleRightWrapped())
585     {
586       LABEL_EAST = fm.stringWidth(getMask());
587     }
588
589     if (av.getScaleLeftWrapped())
590     {
591       LABEL_WEST = fm.stringWidth(getMask());
592     }
593
594     int hgap = charHeight;
595     if (av.getScaleAboveWrapped())
596     {
597       hgap += charHeight;
598     }
599
600     int cWidth = (canvasWidth - LABEL_EAST - LABEL_WEST) / charWidth;
601     int cHeight = av.getAlignment().getHeight() * charHeight;
602
603     av.setWrappedWidth(cWidth);
604
605     av.getRanges().setViewportStartAndWidth(startRes, cWidth);
606
607     int endx;
608     int ypos = hgap;
609     int maxwidth = av.getAlignment().getWidth();
610
611     if (av.hasHiddenColumns())
612     {
613       maxwidth = av.getAlignment().getHiddenColumns()
614               .findColumnPosition(maxwidth);
615     }
616
617     while ((ypos <= canvasHeight) && (startRes < maxwidth))
618     {
619       endx = startRes + cWidth - 1;
620
621       if (endx > maxwidth)
622       {
623         endx = maxwidth;
624       }
625
626       g.setFont(av.getFont());
627       g.setColor(Color.black);
628
629       if (av.getScaleLeftWrapped())
630       {
631         drawWestScale(g, startRes, endx, ypos);
632       }
633
634       if (av.getScaleRightWrapped())
635       {
636         g.translate(canvasWidth - LABEL_EAST, 0);
637         drawEastScale(g, startRes, endx, ypos);
638         g.translate(-(canvasWidth - LABEL_EAST), 0);
639       }
640
641       g.translate(LABEL_WEST, 0);
642
643       if (av.getScaleAboveWrapped())
644       {
645         drawNorthScale(g, startRes, endx, ypos);
646       }
647
648       if (av.hasHiddenColumns() && av.getShowHiddenMarkers())
649       {
650         g.setColor(Color.blue);
651         int res;
652         HiddenColumns hidden = av.getAlignment().getHiddenColumns();
653         List<Integer> positions = hidden.findHiddenRegionPositions();
654         for (int pos : positions)
655         {
656           res = pos - startRes;
657
658           if (res < 0 || res > endx - startRes)
659           {
660             continue;
661           }
662
663           gg.fillPolygon(
664                   new int[]
665                   { res * charWidth - charHeight / 4,
666                       res * charWidth + charHeight / 4, res * charWidth },
667                   new int[]
668                   { ypos - (charHeight / 2), ypos - (charHeight / 2),
669                       ypos - (charHeight / 2) + 8 },
670                   3);
671
672         }
673       }
674
675       // When printing we have an extra clipped region,
676       // the Printable page which we need to account for here
677       Shape clip = g.getClip();
678
679       if (clip == null)
680       {
681         g.setClip(0, 0, cWidth * charWidth, canvasHeight);
682       }
683       else
684       {
685         g.setClip(0, (int) clip.getBounds().getY(), cWidth * charWidth,
686                 (int) clip.getBounds().getHeight());
687       }
688
689       drawPanel(g, startRes, endx, 0, al.getHeight() - 1, ypos);
690
691       if (av.isShowAnnotation())
692       {
693         g.translate(0, cHeight + ypos + 3);
694         if (annotations == null)
695         {
696           annotations = new AnnotationPanel(av);
697         }
698
699         annotations.renderer.drawComponent(annotations, av, g, -1, startRes,
700                 endx + 1);
701         g.translate(0, -cHeight - ypos - 3);
702       }
703       g.setClip(clip);
704       g.translate(-LABEL_WEST, 0);
705
706       ypos += cHeight + getAnnotationHeight() + hgap;
707
708       startRes += cWidth;
709     }
710   }
711
712   /*
713    * Draw a selection group over a wrapped alignment
714    */
715   private void drawWrappedSelection(Graphics2D g, SequenceGroup group,
716           int canvasWidth,
717           int canvasHeight, int startRes)
718   {
719     // height gap above each panel
720     int hgap = charHeight;
721     if (av.getScaleAboveWrapped())
722     {
723       hgap += charHeight;
724     }
725
726     int cWidth = (canvasWidth - LABEL_EAST - LABEL_WEST) / charWidth;
727     int cHeight = av.getAlignment().getHeight() * charHeight;
728
729     int startx = startRes;
730     int endx;
731     int ypos = hgap; // vertical offset
732     int maxwidth = av.getAlignment().getWidth();
733
734     if (av.hasHiddenColumns())
735     {
736       maxwidth = av.getAlignment().getHiddenColumns()
737               .findColumnPosition(maxwidth);
738     }
739
740     // chop the wrapped alignment extent up into panel-sized blocks and treat
741     // each block as if it were a block from an unwrapped alignment
742     while ((ypos <= canvasHeight) && (startx < maxwidth))
743     {
744       // set end value to be start + width, or maxwidth, whichever is smaller
745       endx = startx + cWidth - 1;
746
747       if (endx > maxwidth)
748       {
749         endx = maxwidth;
750       }
751
752       g.translate(LABEL_WEST, 0);
753
754       drawUnwrappedSelection(g, group, startx, endx, 0,
755               av.getAlignment().getHeight() - 1,
756               ypos);
757
758       g.translate(-LABEL_WEST, 0);
759
760       // update vertical offset
761       ypos += cHeight + getAnnotationHeight() + hgap;
762
763       // update horizontal offset
764       startx += cWidth;
765     }
766   }
767
768   int getAnnotationHeight()
769   {
770     if (!av.isShowAnnotation())
771     {
772       return 0;
773     }
774
775     if (annotations == null)
776     {
777       annotations = new AnnotationPanel(av);
778     }
779
780     return annotations.adjustPanelHeight();
781   }
782
783   /*
784    * Draw an alignment panel for printing
785    * 
786    * @param g1
787    *          Graphics object to draw with
788    * @param startRes
789    *          start residue of print area
790    * @param endRes
791    *          end residue of print area
792    * @param startSeq
793    *          start sequence of print area
794    * @param endSeq
795    *          end sequence of print area
796    * @param offset
797    *          vertical offset
798    */
799   private void drawPanel(Graphics g1, int startRes, int endRes,
800           int startSeq, int endSeq, int offset)
801   {
802     updateViewport();
803     if (!av.hasHiddenColumns())
804     {
805       draw(g1, startRes, endRes, startSeq, endSeq, offset);
806     }
807     else
808     {
809       int screenY = 0;
810       int blockStart = startRes;
811       int blockEnd = endRes;
812
813       for (int[] region : av.getAlignment().getHiddenColumns()
814               .getHiddenColumnsCopy())
815       {
816         int hideStart = region[0];
817         int hideEnd = region[1];
818
819         if (hideStart <= blockStart)
820         {
821           blockStart += (hideEnd - hideStart) + 1;
822           continue;
823         }
824
825         blockEnd = hideStart - 1;
826
827         g1.translate(screenY * charWidth, 0);
828
829         draw(g1, blockStart, blockEnd, startSeq, endSeq, offset);
830
831         if (av.getShowHiddenMarkers())
832         {
833           g1.setColor(Color.blue);
834
835           g1.drawLine((blockEnd - blockStart + 1) * charWidth - 1,
836                   0 + offset, (blockEnd - blockStart + 1) * charWidth - 1,
837                   (endSeq - startSeq + 1) * charHeight + offset);
838         }
839
840         g1.translate(-screenY * charWidth, 0);
841         screenY += blockEnd - blockStart + 1;
842         blockStart = hideEnd + 1;
843
844         if (screenY > (endRes - startRes))
845         {
846           // already rendered last block
847           return;
848         }
849       }
850
851       if (screenY <= (endRes - startRes))
852       {
853         // remaining visible region to render
854         blockEnd = blockStart + (endRes - startRes) - screenY;
855         g1.translate(screenY * charWidth, 0);
856         draw(g1, blockStart, blockEnd, startSeq, endSeq, offset);
857
858         g1.translate(-screenY * charWidth, 0);
859       }
860     }
861
862   }
863
864   private void draw(Graphics g, int startRes, int endRes, int startSeq,
865           int endSeq, int offset)
866   {
867     g.setFont(av.getFont());
868     seqRdr.prepare(g, av.isRenderGaps());
869
870     SequenceI nextSeq;
871
872     // / First draw the sequences
873     // ///////////////////////////
874     for (int i = startSeq; i <= endSeq; i++)
875     {
876       nextSeq = av.getAlignment().getSequenceAt(i);
877       if (nextSeq == null)
878       {
879         // occasionally, a race condition occurs such that the alignment row is
880         // empty
881         continue;
882       }
883       seqRdr.drawSequence(nextSeq, av.getAlignment().findAllGroups(nextSeq),
884               startRes, endRes, offset + ((i - startSeq) * charHeight));
885
886       if (av.isShowSequenceFeatures())
887       {
888         fr.drawSequence(g, nextSeq, startRes, endRes,
889                 offset + ((i - startSeq) * charHeight), false);
890       }
891
892       // / Highlight search Results once all sequences have been drawn
893       // ////////////////////////////////////////////////////////
894       if (av.hasSearchResults())
895       {
896         int[] visibleResults = av.getSearchResults().getResults(nextSeq,
897                 startRes, endRes);
898         if (visibleResults != null)
899         {
900           for (int r = 0; r < visibleResults.length; r += 2)
901           {
902             seqRdr.drawHighlightedText(nextSeq, visibleResults[r],
903                     visibleResults[r + 1], (visibleResults[r] - startRes)
904                             * charWidth, offset
905                             + ((i - startSeq) * charHeight));
906           }
907         }
908       }
909
910       if (av.cursorMode && cursorY == i && cursorX >= startRes
911               && cursorX <= endRes)
912       {
913         seqRdr.drawCursor(nextSeq, cursorX, (cursorX - startRes) * charWidth,
914                 offset + ((i - startSeq) * charHeight));
915       }
916     }
917
918     if (av.getSelectionGroup() != null
919             || av.getAlignment().getGroups().size() > 0)
920     {
921       drawGroupsBoundaries(g, startRes, endRes, startSeq, endSeq, offset);
922     }
923
924   }
925
926   void drawGroupsBoundaries(Graphics g1, int startRes, int endRes,
927           int startSeq, int endSeq, int offset)
928   {
929     Graphics2D g = (Graphics2D) g1;
930     //
931     // ///////////////////////////////////
932     // Now outline any areas if necessary
933     // ///////////////////////////////////
934
935     SequenceGroup group = null;
936     int groupIndex = -1;
937
938     if (av.getAlignment().getGroups().size() > 0)
939     {
940       group = av.getAlignment().getGroups().get(0);
941       groupIndex = 0;
942     }
943
944     if (group != null)
945     {
946       g.setStroke(new BasicStroke());
947       g.setColor(group.getOutlineColour());
948       
949       do
950       {
951         drawPartialGroupOutline(g, group, startRes, endRes, startSeq,
952                 endSeq, offset);
953
954         groupIndex++;
955
956         g.setStroke(new BasicStroke());
957
958         if (groupIndex >= av.getAlignment().getGroups().size())
959         {
960           break;
961         }
962
963         group = av.getAlignment().getGroups().get(groupIndex);
964
965       } while (groupIndex < av.getAlignment().getGroups().size());
966
967     }
968
969   }
970
971
972   /*
973    * Draw the selection group as a separate image and overlay
974    */
975   private BufferedImage drawSelectionGroup(int startRes, int endRes,
976           int startSeq, int endSeq)
977   {
978     // get a new image of the correct size
979     BufferedImage selectionImage = setupImage();
980
981     if (selectionImage == null)
982     {
983       return null;
984     }
985
986     SequenceGroup group = av.getSelectionGroup();
987     if (group == null)
988     {
989       // nothing to draw
990       return null;
991     }
992
993     // set up drawing colour
994     Graphics2D g = (Graphics2D) selectionImage.getGraphics();
995
996     // set background to transparent
997     g.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f));
998     g.fillRect(0, 0, selectionImage.getWidth(), selectionImage.getHeight());
999
1000     // set up foreground to draw red dashed line
1001     g.setComposite(AlphaComposite.Src);
1002     g.setStroke(new BasicStroke(1, BasicStroke.CAP_BUTT,
1003             BasicStroke.JOIN_ROUND, 3f, new float[]
1004     { 5f, 3f }, 0f));
1005     g.setColor(Color.RED);
1006
1007     if (!av.getWrapAlignment())
1008     {
1009       drawUnwrappedSelection(g, group, startRes, endRes, startSeq, endSeq,
1010               0);
1011     }
1012     else
1013     {
1014       drawWrappedSelection(g, group, getWidth(), getHeight(),
1015               av.getRanges().getStartRes());
1016     }
1017
1018     g.dispose();
1019     return selectionImage;
1020   }
1021
1022   /*
1023    * Draw a selection group over an unwrapped alignment
1024    * @param g graphics object to draw with
1025    * @param group selection group
1026    * @param startRes start residue of area to draw
1027    * @param endRes end residue of area to draw
1028    * @param startSeq start sequence of area to draw
1029    * @param endSeq end sequence of area to draw
1030    * @param offset vertical offset (used when called from wrapped alignment code)
1031    */
1032   private void drawUnwrappedSelection(Graphics2D g, SequenceGroup group,
1033           int startRes, int endRes, int startSeq, int endSeq, int offset)
1034   {
1035     if (!av.hasHiddenColumns())
1036     {
1037       drawPartialGroupOutline(g, group, startRes, endRes, startSeq, endSeq,
1038               offset);
1039     }
1040     else
1041     {
1042       // package into blocks of visible columns
1043       int screenY = 0;
1044       int blockStart = startRes;
1045       int blockEnd = endRes;
1046
1047       for (int[] region : av.getAlignment().getHiddenColumns()
1048               .getHiddenColumnsCopy())
1049       {
1050         int hideStart = region[0];
1051         int hideEnd = region[1];
1052
1053         if (hideStart <= blockStart)
1054         {
1055           blockStart += (hideEnd - hideStart) + 1;
1056           continue;
1057         }
1058
1059         blockEnd = hideStart - 1;
1060
1061         g.translate(screenY * charWidth, 0);
1062         drawPartialGroupOutline(g, group,
1063                 blockStart, blockEnd, startSeq, endSeq, offset);
1064
1065         g.translate(-screenY * charWidth, 0);
1066         screenY += blockEnd - blockStart + 1;
1067         blockStart = hideEnd + 1;
1068
1069         if (screenY > (endRes - startRes))
1070         {
1071           // already rendered last block
1072           break;
1073         }
1074       }
1075
1076       if (screenY <= (endRes - startRes))
1077       {
1078         // remaining visible region to render
1079         blockEnd = blockStart + (endRes - startRes) - screenY;
1080         g.translate(screenY * charWidth, 0);
1081         drawPartialGroupOutline(g, group,
1082                 blockStart, blockEnd, startSeq, endSeq, offset);
1083         
1084         g.translate(-screenY * charWidth, 0);
1085       }
1086     }
1087   }
1088
1089   /*
1090    * Draw the selection group as a separate image and overlay
1091    */
1092   private void drawPartialGroupOutline(Graphics2D g, SequenceGroup group,
1093           int startRes, int endRes, int startSeq, int endSeq,
1094           int verticalOffset)
1095   {
1096     int visWidth = (endRes - startRes + 1) * charWidth;
1097
1098     int oldY = -1;
1099     int i = 0;
1100     boolean inGroup = false;
1101     int top = -1;
1102     int bottom = -1;
1103
1104     int sx = -1;
1105     int sy = -1;
1106     int xwidth = -1;
1107
1108     for (i = startSeq; i <= endSeq; i++)
1109     {
1110       // position of start residue of group relative to startRes, in pixels
1111       sx = (group.getStartRes() - startRes) * charWidth;
1112
1113       // width of group in pixels
1114       xwidth = (((group.getEndRes() + 1) - group.getStartRes()) * charWidth)
1115               - 1;
1116
1117       sy = verticalOffset + (i - startSeq) * charHeight;
1118
1119       if (sx + xwidth < 0 || sx > visWidth)
1120       {
1121         continue;
1122       }
1123
1124       if ((sx <= (endRes - startRes) * charWidth)
1125               && group.getSequences(null)
1126                       .contains(av.getAlignment().getSequenceAt(i)))
1127       {
1128         if ((bottom == -1) && !group.getSequences(null)
1129                 .contains(av.getAlignment().getSequenceAt(i + 1)))
1130         {
1131           bottom = sy + charHeight;
1132         }
1133
1134         if (!inGroup)
1135         {
1136           if (((top == -1) && (i == 0)) || !group.getSequences(null)
1137                   .contains(av.getAlignment().getSequenceAt(i - 1)))
1138           {
1139             top = sy;
1140           }
1141
1142           oldY = sy;
1143           inGroup = true;
1144         }
1145       }
1146       else
1147       {
1148         if (inGroup)
1149         {
1150           // if start position is visible, draw vertical line to left of
1151           // group
1152           if (sx >= 0 && sx < visWidth)
1153           {
1154             g.drawLine(sx, oldY, sx, sy);
1155           }
1156
1157           // if end position is visible, draw vertical line to right of
1158           // group
1159           if (sx + xwidth < visWidth)
1160           {
1161             g.drawLine(sx + xwidth, oldY, sx + xwidth, sy);
1162           }
1163
1164           if (sx < 0)
1165           {
1166             xwidth += sx;
1167             sx = 0;
1168           }
1169
1170           // don't let width extend beyond current block, or group extent
1171           // fixes JAL-2672
1172           if (sx + xwidth >= (endRes - startRes + 1) * charWidth)
1173           {
1174             xwidth = (endRes - startRes + 1) * charWidth - sx;
1175           }
1176           
1177           // draw horizontal line at top of group
1178           if (top != -1)
1179           {
1180             g.drawLine(sx, top, sx + xwidth, top);
1181             top = -1;
1182           }
1183
1184           // draw horizontal line at bottom of group
1185           if (bottom != -1)
1186           {
1187             g.drawLine(sx, bottom, sx + xwidth, bottom);
1188             bottom = -1;
1189           }
1190
1191           inGroup = false;
1192         }
1193       }
1194     }
1195
1196     if (inGroup)
1197     {
1198       sy = verticalOffset + ((i - startSeq) * charHeight);
1199       if (sx >= 0 && sx < visWidth)
1200       {
1201         g.drawLine(sx, oldY, sx, sy);
1202       }
1203
1204       if (sx + xwidth < visWidth)
1205       {
1206         g.drawLine(sx + xwidth, oldY, sx + xwidth, sy);
1207       }
1208
1209       if (sx < 0)
1210       {
1211         xwidth += sx;
1212         sx = 0;
1213       }
1214
1215       if (sx + xwidth > visWidth)
1216       {
1217         xwidth = visWidth;
1218       }
1219       else if (sx + xwidth >= (endRes - startRes + 1) * charWidth)
1220       {
1221         xwidth = (endRes - startRes + 1) * charWidth;
1222       }
1223
1224       if (top != -1)
1225       {
1226         g.drawLine(sx, top, sx + xwidth, top);
1227         top = -1;
1228       }
1229
1230       if (bottom != -1)
1231       {
1232         g.drawLine(sx, bottom - 1, sx + xwidth, bottom - 1);
1233         bottom = -1;
1234       }
1235
1236       inGroup = false;
1237     }
1238   }
1239   
1240   /**
1241    * DOCUMENT ME!
1242    * 
1243    * @param results
1244    *          DOCUMENT ME!
1245    */
1246   public void highlightSearchResults(SearchResultsI results)
1247   {
1248     img = null;
1249
1250     av.setSearchResults(results);
1251
1252     repaint();
1253   }
1254
1255   @Override
1256   public void propertyChange(PropertyChangeEvent evt)
1257   {
1258     String eventName = evt.getPropertyName();
1259
1260     if (eventName.equals(SequenceGroup.SEQ_GROUP_CHANGED))
1261     {
1262       fastPaint = true;
1263       repaint();
1264     }
1265     else if (av.getWrapAlignment())
1266     {
1267       if (eventName.equals(ViewportRanges.STARTRES))
1268       {
1269         repaint();
1270       }
1271     }
1272     else
1273     {
1274       int scrollX = 0;
1275       if (eventName.equals(ViewportRanges.STARTRES))
1276       {
1277         // Make sure we're not trying to draw a panel
1278         // larger than the visible window
1279         ViewportRanges vpRanges = av.getRanges();
1280         scrollX = (int) evt.getNewValue() - (int) evt.getOldValue();
1281         int range = vpRanges.getEndRes() - vpRanges.getStartRes();
1282         if (scrollX > range)
1283         {
1284           scrollX = range;
1285         }
1286         else if (scrollX < -range)
1287         {
1288           scrollX = -range;
1289         }
1290       }
1291
1292       // Both scrolling and resizing change viewport ranges: scrolling changes
1293       // both start and end points, but resize only changes end values.
1294       // Here we only want to fastpaint on a scroll, with resize using a normal
1295       // paint, so scroll events are identified as changes to the horizontal or
1296       // vertical start value.
1297       if (eventName.equals(ViewportRanges.STARTRES))
1298       {
1299         // scroll - startres and endres both change
1300         fastPaint(scrollX, 0);
1301       }
1302       else if (eventName.equals(ViewportRanges.STARTSEQ))
1303       {
1304         // scroll
1305         fastPaint(0, (int) evt.getNewValue() - (int) evt.getOldValue());
1306       }
1307     }
1308   }
1309 }