955a9e6fe5b60f990bb6943f0eba3805116c5359
[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), (ypos + 2)
151                 - (charHeight / 2), (mpos * charWidth) + (charWidth / 2),
152                 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, (ypos + (i * charHeight))
215                 - (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, (ypos + (i * charHeight))
267                 - (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[] { res * charWidth - charHeight / 4,
665                       res * charWidth + charHeight / 4, res * charWidth },
666                   new int[] { ypos - (charHeight / 2),
667                       ypos - (charHeight / 2), ypos - (charHeight / 2) + 8 },
668                   3);
669
670         }
671       }
672
673       // When printing we have an extra clipped region,
674       // the Printable page which we need to account for here
675       Shape clip = g.getClip();
676
677       if (clip == null)
678       {
679         g.setClip(0, 0, cWidth * charWidth, canvasHeight);
680       }
681       else
682       {
683         g.setClip(0, (int) clip.getBounds().getY(), cWidth * charWidth,
684                 (int) clip.getBounds().getHeight());
685       }
686
687       drawPanel(g, startRes, endx, 0, al.getHeight() - 1, ypos);
688
689       if (av.isShowAnnotation())
690       {
691         g.translate(0, cHeight + ypos + 3);
692         if (annotations == null)
693         {
694           annotations = new AnnotationPanel(av);
695         }
696
697         annotations.renderer.drawComponent(annotations, av, g, -1,
698                 startRes, endx + 1);
699         g.translate(0, -cHeight - ypos - 3);
700       }
701       g.setClip(clip);
702       g.translate(-LABEL_WEST, 0);
703
704       ypos += cHeight + getAnnotationHeight() + hgap;
705
706       startRes += cWidth;
707     }
708   }
709
710   /*
711    * Draw a selection group over a wrapped alignment
712    */
713   private void drawWrappedSelection(Graphics2D g, SequenceGroup group,
714           int canvasWidth,
715           int canvasHeight, int startRes)
716   {
717     // height gap above each panel
718     int hgap = charHeight;
719     if (av.getScaleAboveWrapped())
720     {
721       hgap += charHeight;
722     }
723
724     int cWidth = (canvasWidth - LABEL_EAST - LABEL_WEST) / charWidth;
725     int cHeight = av.getAlignment().getHeight() * charHeight;
726
727     int startx = startRes;
728     int endx;
729     int ypos = hgap; // vertical offset
730     int maxwidth = av.getAlignment().getWidth();
731
732     if (av.hasHiddenColumns())
733     {
734       maxwidth = av.getAlignment().getHiddenColumns()
735               .findColumnPosition(maxwidth);
736     }
737
738     // chop the wrapped alignment extent up into panel-sized blocks and treat
739     // each block as if it were a block from an unwrapped alignment
740     while ((ypos <= canvasHeight) && (startx < maxwidth))
741     {
742       // set end value to be start + width, or maxwidth, whichever is smaller
743       endx = startx + cWidth - 1;
744
745       if (endx > maxwidth)
746       {
747         endx = maxwidth;
748       }
749
750       g.translate(LABEL_WEST, 0);
751
752       drawUnwrappedSelection(g, group, startx, endx, 0,
753               av.getAlignment().getHeight() - 1,
754               ypos);
755
756       g.translate(-LABEL_WEST, 0);
757
758       // update vertical offset
759       ypos += cHeight + getAnnotationHeight() + hgap;
760
761       // update horizontal offset
762       startx += cWidth;
763     }
764   }
765
766   int getAnnotationHeight()
767   {
768     if (!av.isShowAnnotation())
769     {
770       return 0;
771     }
772
773     if (annotations == null)
774     {
775       annotations = new AnnotationPanel(av);
776     }
777
778     return annotations.adjustPanelHeight();
779   }
780
781   /*
782    * Draw an alignment panel for printing
783    * 
784    * @param g1
785    *          Graphics object to draw with
786    * @param startRes
787    *          start residue of print area
788    * @param endRes
789    *          end residue of print area
790    * @param startSeq
791    *          start sequence of print area
792    * @param endSeq
793    *          end sequence of print area
794    * @param offset
795    *          vertical offset
796    */
797   private void drawPanel(Graphics g1, int startRes, int endRes,
798           int startSeq, int endSeq, int offset)
799   {
800     updateViewport();
801     if (!av.hasHiddenColumns())
802     {
803       draw(g1, startRes, endRes, startSeq, endSeq, offset);
804     }
805     else
806     {
807       int screenY = 0;
808       int blockStart = startRes;
809       int blockEnd = endRes;
810
811       for (int[] region : av.getAlignment().getHiddenColumns()
812               .getHiddenColumnsCopy())
813       {
814         int hideStart = region[0];
815         int hideEnd = region[1];
816
817         if (hideStart <= blockStart)
818         {
819           blockStart += (hideEnd - hideStart) + 1;
820           continue;
821         }
822
823         blockEnd = hideStart - 1;
824
825         g1.translate(screenY * charWidth, 0);
826
827         draw(g1, blockStart, blockEnd, startSeq, endSeq, offset);
828
829         if (av.getShowHiddenMarkers())
830         {
831           g1.setColor(Color.blue);
832
833           g1.drawLine((blockEnd - blockStart + 1) * charWidth - 1,
834                   0 + offset, (blockEnd - blockStart + 1) * charWidth - 1,
835                   (endSeq - startSeq + 1) * charHeight + offset);
836         }
837
838         g1.translate(-screenY * charWidth, 0);
839         screenY += blockEnd - blockStart + 1;
840         blockStart = hideEnd + 1;
841
842         if (screenY > (endRes - startRes))
843         {
844           // already rendered last block
845           return;
846         }
847       }
848
849       if (screenY <= (endRes - startRes))
850       {
851         // remaining visible region to render
852         blockEnd = blockStart + (endRes - startRes) - screenY;
853         g1.translate(screenY * charWidth, 0);
854         draw(g1, blockStart, blockEnd, startSeq, endSeq, offset);
855
856         g1.translate(-screenY * charWidth, 0);
857       }
858     }
859
860   }
861
862   private void draw(Graphics g, int startRes, int endRes, int startSeq,
863           int endSeq, int offset)
864   {
865     g.setFont(av.getFont());
866     seqRdr.prepare(g, av.isRenderGaps());
867
868     SequenceI nextSeq;
869
870     // / First draw the sequences
871     // ///////////////////////////
872     for (int i = startSeq; i <= endSeq; i++)
873     {
874       nextSeq = av.getAlignment().getSequenceAt(i);
875       if (nextSeq == null)
876       {
877         // occasionally, a race condition occurs such that the alignment row is
878         // empty
879         continue;
880       }
881       seqRdr.drawSequence(nextSeq, av.getAlignment().findAllGroups(nextSeq),
882               startRes, endRes, offset + ((i - startSeq) * charHeight));
883
884       if (av.isShowSequenceFeatures())
885       {
886         fr.drawSequence(g, nextSeq, startRes, endRes, offset
887                 + ((i - startSeq) * charHeight), false);
888       }
889
890       // / Highlight search Results once all sequences have been drawn
891       // ////////////////////////////////////////////////////////
892       if (av.hasSearchResults())
893       {
894         int[] visibleResults = av.getSearchResults().getResults(nextSeq,
895                 startRes, endRes);
896         if (visibleResults != null)
897         {
898           for (int r = 0; r < visibleResults.length; r += 2)
899           {
900             seqRdr.drawHighlightedText(nextSeq, visibleResults[r],
901                     visibleResults[r + 1], (visibleResults[r] - startRes)
902                             * charWidth, offset
903                             + ((i - startSeq) * charHeight));
904           }
905         }
906       }
907
908       if (av.cursorMode && cursorY == i && cursorX >= startRes
909               && cursorX <= endRes)
910       {
911         seqRdr.drawCursor(nextSeq, cursorX, (cursorX - startRes) * charWidth,
912                 offset + ((i - startSeq) * charHeight));
913       }
914     }
915
916     if (av.getSelectionGroup() != null
917             || av.getAlignment().getGroups().size() > 0)
918     {
919       drawGroupsBoundaries(g, startRes, endRes, startSeq, endSeq, offset);
920     }
921
922   }
923
924   void drawGroupsBoundaries(Graphics g1, int startRes, int endRes,
925           int startSeq, int endSeq, int offset)
926   {
927     Graphics2D g = (Graphics2D) g1;
928     //
929     // ///////////////////////////////////
930     // Now outline any areas if necessary
931     // ///////////////////////////////////
932
933     SequenceGroup group = null;
934     int groupIndex = -1;
935
936     if (av.getAlignment().getGroups().size() > 0)
937     {
938       group = av.getAlignment().getGroups().get(0);
939       groupIndex = 0;
940     }
941
942     if (group != null)
943     {
944       g.setStroke(new BasicStroke());
945       g.setColor(group.getOutlineColour());
946       
947       do
948       {
949         drawPartialGroupOutline(g, group, startRes, endRes, startSeq,
950                 endSeq, offset);
951         
952         groupIndex++;
953
954         g.setStroke(new BasicStroke());
955
956         if (groupIndex >= av.getAlignment().getGroups().size())
957         {
958           break;
959         }
960
961         group = av.getAlignment().getGroups().get(groupIndex);
962
963       } while (groupIndex < av.getAlignment().getGroups().size());
964
965     }
966
967   }
968
969
970   /*
971    * Draw the selection group as a separate image and overlay
972    */
973   private BufferedImage drawSelectionGroup(int startRes, int endRes,
974           int startSeq, int endSeq)
975   {
976     // get a new image of the correct size
977     BufferedImage selectionImage = setupImage();
978
979     if (selectionImage == null)
980     {
981       return null;
982     }
983
984     SequenceGroup group = av.getSelectionGroup();
985     if (group == null)
986     {
987       // nothing to draw
988       return null;
989     }
990
991     // set up drawing colour
992     Graphics2D g = (Graphics2D) selectionImage.getGraphics();
993
994     // set background to transparent
995     g.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f));
996     g.fillRect(0, 0, selectionImage.getWidth(), selectionImage.getHeight());
997
998     // set up foreground to draw red dashed line
999     g.setComposite(AlphaComposite.Src);
1000     g.setStroke(new BasicStroke(1, BasicStroke.CAP_BUTT,
1001             BasicStroke.JOIN_ROUND, 3f, new float[]
1002     { 5f, 3f }, 0f));
1003     g.setColor(Color.RED);
1004
1005     if (!av.getWrapAlignment())
1006     {
1007       drawUnwrappedSelection(g, group, startRes, endRes, startSeq, endSeq,
1008               0);
1009     }
1010     else
1011     {
1012       drawWrappedSelection(g, group, getWidth(), getHeight(),
1013               av.getRanges().getStartRes());
1014     }
1015
1016     g.dispose();
1017     return selectionImage;
1018   }
1019
1020   /*
1021    * Draw a selection group over an unwrapped alignment
1022    * @param g graphics object to draw with
1023    * @param group selection group
1024    * @param startRes start residue of area to draw
1025    * @param endRes end residue of area to draw
1026    * @param startSeq start sequence of area to draw
1027    * @param endSeq end sequence of area to draw
1028    * @param offset vertical offset (used when called from wrapped alignment code)
1029    */
1030   private void drawUnwrappedSelection(Graphics2D g, SequenceGroup group,
1031           int startRes, int endRes, int startSeq, int endSeq, int offset)
1032   {
1033     if (!av.hasHiddenColumns())
1034     {
1035       drawPartialGroupOutline(g, group, startRes, endRes, startSeq, endSeq,
1036               offset);
1037     }
1038     else
1039     {
1040       // package into blocks of visible columns
1041       int screenY = 0;
1042       int blockStart = startRes;
1043       int blockEnd = endRes;
1044
1045       for (int[] region : av.getAlignment().getHiddenColumns()
1046               .getHiddenColumnsCopy())
1047       {
1048         int hideStart = region[0];
1049         int hideEnd = region[1];
1050
1051         if (hideStart <= blockStart)
1052         {
1053           blockStart += (hideEnd - hideStart) + 1;
1054           continue;
1055         }
1056
1057         blockEnd = hideStart - 1;
1058
1059         g.translate(screenY * charWidth, 0);
1060         drawPartialGroupOutline(g, group,
1061                 blockStart, blockEnd, startSeq, endSeq, offset);
1062
1063         g.translate(-screenY * charWidth, 0);
1064         screenY += blockEnd - blockStart + 1;
1065         blockStart = hideEnd + 1;
1066
1067         if (screenY > (endRes - startRes))
1068         {
1069           // already rendered last block
1070           break;
1071         }
1072       }
1073
1074       if (screenY <= (endRes - startRes))
1075       {
1076         // remaining visible region to render
1077         blockEnd = blockStart + (endRes - startRes) - screenY;
1078         g.translate(screenY * charWidth, 0);
1079         drawPartialGroupOutline(g, group,
1080                 blockStart, blockEnd, startSeq, endSeq, offset);
1081         
1082         g.translate(-screenY * charWidth, 0);
1083       }
1084     }
1085   }
1086
1087   /*
1088    * Draw the selection group as a separate image and overlay
1089    */
1090   private void drawPartialGroupOutline(Graphics2D g, SequenceGroup group,
1091           int startRes, int endRes, int startSeq, int endSeq,
1092           int verticalOffset)
1093   {
1094     int visWidth = (endRes - startRes + 1) * charWidth;
1095
1096     int oldY = -1;
1097     int i = 0;
1098     boolean inGroup = false;
1099     int top = -1;
1100     int bottom = -1;
1101
1102     int sx = -1;
1103     int sy = -1;
1104     int xwidth = -1;
1105
1106     for (i = startSeq; i <= endSeq; i++)
1107     {
1108       // position of start residue of group relative to startRes, in pixels
1109       sx = (group.getStartRes() - startRes) * charWidth;
1110
1111       // width of group in pixels
1112       xwidth = (((group.getEndRes() + 1) - group.getStartRes()) * charWidth)
1113               - 1;
1114
1115       sy = verticalOffset + (i - startSeq) * charHeight;
1116
1117       if (sx + xwidth < 0 || sx > visWidth)
1118       {
1119         continue;
1120       }
1121
1122       if ((sx <= (endRes - startRes) * charWidth)
1123               && group.getSequences(null)
1124                       .contains(av.getAlignment().getSequenceAt(i)))
1125       {
1126         if ((bottom == -1) && !group.getSequences(null)
1127                 .contains(av.getAlignment().getSequenceAt(i + 1)))
1128         {
1129           bottom = sy + charHeight;
1130         }
1131
1132         if (!inGroup)
1133         {
1134           if (((top == -1) && (i == 0)) || !group.getSequences(null)
1135                   .contains(av.getAlignment().getSequenceAt(i - 1)))
1136           {
1137             top = sy;
1138           }
1139
1140           oldY = sy;
1141           inGroup = true;
1142         }
1143       }
1144       else
1145       {
1146         if (inGroup)
1147         {
1148           // if start position is visible, draw vertical line to left of
1149           // group
1150           if (sx >= 0 && sx < visWidth)
1151           {
1152             g.drawLine(sx, oldY, sx, sy);
1153           }
1154
1155           // if end position is visible, draw vertical line to right of
1156           // group
1157           if (sx + xwidth < visWidth)
1158           {
1159             g.drawLine(sx + xwidth, oldY, sx + xwidth, sy);
1160           }
1161
1162           if (sx < 0)
1163           {
1164             xwidth += sx;
1165             sx = 0;
1166           }
1167
1168           // don't let width extend beyond current block, or group extent
1169           // fixes JAL-2672
1170           if (sx + xwidth >= (endRes - startRes + 1) * charWidth)
1171           {
1172             xwidth = (endRes - startRes + 1) * charWidth - sx;
1173           }
1174           
1175           // draw horizontal line at top of group
1176           if (top != -1)
1177           {
1178             g.drawLine(sx, top, sx + xwidth, top);
1179             top = -1;
1180           }
1181
1182           // draw horizontal line at bottom of group
1183           if (bottom != -1)
1184           {
1185             g.drawLine(sx, bottom, sx + xwidth, bottom);
1186             bottom = -1;
1187           }
1188
1189           inGroup = false;
1190         }
1191       }
1192     }
1193
1194     if (inGroup)
1195     {
1196       sy = verticalOffset + ((i - startSeq) * charHeight);
1197       if (sx >= 0 && sx < visWidth)
1198       {
1199         g.drawLine(sx, oldY, sx, sy);
1200       }
1201
1202       if (sx + xwidth < visWidth)
1203       {
1204         g.drawLine(sx + xwidth, oldY, sx + xwidth, sy);
1205       }
1206
1207       if (sx < 0)
1208       {
1209         xwidth += sx;
1210         sx = 0;
1211       }
1212
1213       if (sx + xwidth > visWidth)
1214       {
1215         xwidth = visWidth;
1216       }
1217       else if (sx + xwidth >= (endRes - startRes + 1) * charWidth)
1218       {
1219         xwidth = (endRes - startRes + 1) * charWidth;
1220       }
1221
1222       if (top != -1)
1223       {
1224         g.drawLine(sx, top, sx + xwidth, top);
1225         top = -1;
1226       }
1227
1228       if (bottom != -1)
1229       {
1230         g.drawLine(sx, bottom - 1, sx + xwidth, bottom - 1);
1231         bottom = -1;
1232       }
1233
1234       inGroup = false;
1235     }
1236   }
1237   
1238   /**
1239    * DOCUMENT ME!
1240    * 
1241    * @param results
1242    *          DOCUMENT ME!
1243    */
1244   public void highlightSearchResults(SearchResultsI results)
1245   {
1246     img = null;
1247
1248     av.setSearchResults(results);
1249
1250     repaint();
1251   }
1252
1253   @Override
1254   public void propertyChange(PropertyChangeEvent evt)
1255   {
1256     String eventName = evt.getPropertyName();
1257
1258     if (eventName.equals(SequenceGroup.SEQ_GROUP_CHANGED))
1259     {
1260       fastPaint = true;
1261       repaint();
1262     }
1263     else if (av.getWrapAlignment())
1264     {
1265       if (eventName.equals(ViewportRanges.STARTRES))
1266       {
1267         repaint();
1268       }
1269     }
1270     else
1271     {
1272       int scrollX = 0;
1273       if (eventName.equals(ViewportRanges.STARTRES))
1274       {
1275         // Make sure we're not trying to draw a panel
1276         // larger than the visible window
1277         ViewportRanges vpRanges = av.getRanges();
1278         scrollX = (int) evt.getNewValue() - (int) evt.getOldValue();
1279         int range = vpRanges.getEndRes() - vpRanges.getStartRes();
1280         if (scrollX > range)
1281         {
1282           scrollX = range;
1283         }
1284         else if (scrollX < -range)
1285         {
1286           scrollX = -range;
1287         }
1288       }
1289
1290       // Both scrolling and resizing change viewport ranges: scrolling changes
1291       // both start and end points, but resize only changes end values.
1292       // Here we only want to fastpaint on a scroll, with resize using a normal
1293       // paint, so scroll events are identified as changes to the horizontal or
1294       // vertical start value.
1295       if (eventName.equals(ViewportRanges.STARTRES))
1296       {
1297         // scroll - startres and endres both change
1298         fastPaint(scrollX, 0);
1299       }
1300       else if (eventName.equals(ViewportRanges.STARTSEQ))
1301       {
1302         // scroll
1303         fastPaint(0, (int) evt.getNewValue() - (int) evt.getOldValue());
1304       }
1305     }
1306   }
1307 }